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(health): a fill ramp for the galaxy, and a calmer file sidebar (#1991)

Raghav Chamadiya5fdd1e5ec1f2
diff --git a/packages/ui/__tests__/health/code-health-map.test.tsx b/packages/ui/__tests__/health/code-health-map.test.tsx
index f6203a640..f3238f251 100644
--- a/packages/ui/__tests__/health/code-health-map.test.tsx
+++ b/packages/ui/__tests__/health/code-health-map.test.tsx
@@ -3,6 +3,7 @@ import { render, fireEvent } from "@testing-library/react";
import {
CodeHealthMap,
MapLegend,
+ NEUTRAL_FILL,
MapLensSwitcher,
groupByModule,
performanceBurden,
@@ -161,14 +162,15 @@ describe("CodeHealthMap", () => {
const fillFor = (path: string) =>
container.querySelector(`circle[data-path="${path}"]`)?.getAttribute("fill");
for (const path of ["core/hot.py", "core/clean.py", "core/leveldb.cc"]) {
- expect(fillFor(path)).not.toBe("var(--color-success)");
+ expect(fillFor(path)).not.toBe("var(--color-node-good)");
}
- // Analysed and unanalysed differ, and neither differs by hue.
- expect(fillFor("core/clean.py")).toBe("var(--color-text-tertiary)");
- expect(fillFor("core/leveldb.cc")).toBe("var(--color-border-default)");
+ // Both take the one neutral. Which of the two a file is cannot be read off
+ // a shade of grey, so the field stops trying and the words carry it.
+ expect(fillFor("core/clean.py")).toBe(NEUTRAL_FILL);
+ expect(fillFor("core/leveldb.cc")).toBe(NEUTRAL_FILL);
});
- it("carries the burden on the node and the plan on the ring", () => {
+ it("carries the burden on the node's own colour, with no second mark", () => {
const files: CodeHealthMapFile[] = [
{ ...f("core/planned.py", 120, "core"), performance_opportunities: 9, performance_actionability: "plan_ready", performance_analyzed: true },
{ ...f("core/one.py", 100, "core"), performance_opportunities: 1, performance_actionability: "investigate", performance_analyzed: true },
@@ -177,21 +179,11 @@ describe("CodeHealthMap", () => {
const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
const fillOf = (p: string) =>
container.querySelector(`circle[data-path="${p}"]`)?.getAttribute("fill");
- expect(fillOf("core/planned.py")).toBe("var(--color-error)");
- expect(fillOf("core/one.py")).toContain("--color-caution");
- expect(fillOf("core/clean.py")).toBe("var(--color-text-tertiary)");
- // The ring is the rare mark, not one every coloured node carries.
- expect(container.querySelector('circle[data-ring="core/planned.py"]')).toBeTruthy();
- expect(container.querySelector('circle[data-ring="core/one.py"]')).toBeNull();
- expect(container.querySelector('circle[data-ring="core/clean.py"]')).toBeNull();
- });
-
- it("draws no ring under any other lens", () => {
- const files: CodeHealthMapFile[] = [
- { ...f("core/many.py", 120, "core"), performance_opportunities: 9, performance_analyzed: true },
- ];
- const { container } = render(<CodeHealthMap files={files} overlay="health" />);
- expect(container.querySelectorAll("circle[data-ring]")).toHaveLength(0);
+ expect(fillOf("core/planned.py")).toBe("var(--color-node-critical)");
+ expect(fillOf("core/one.py")).toBe("var(--color-node-fair)");
+ expect(fillOf("core/clean.py")).toBe(NEUTRAL_FILL);
+ // Stored plan earns no mark of its own. It is said in words instead.
+ expect(container.querySelectorAll("circle[data-plan]")).toHaveLength(0);
});
it("counts observations and says so when the host serves no causal model", () => {
@@ -212,7 +204,7 @@ describe("CodeHealthMap", () => {
it("reports an unknown state when nothing on the row says either way", () => {
const row = f("core/x.py", 10, "core");
expect(performanceBurden(row).state).toBe("unknown");
- expect(performanceFill(row)).toBe("var(--color-border-default)");
+ expect(performanceFill(row)).toBe(NEUTRAL_FILL);
});
it("fires onOverlayChange when a lens-switch button is clicked", () => {
@@ -280,12 +272,14 @@ describe("map chrome, off canvas", () => {
it("MapLegend renders the active lens's bands and caption", () => {
const { getByText } = render(<MapLegend overlay="performance" />);
expect(getByText("5 or more")).toBeInTheDocument();
- expect(getByText("Not analyzed")).toBeInTheDocument();
+ expect(getByText("Nothing surfaced")).toBeInTheDocument();
// The caption refuses the runtime claim the colour could be read as making,
// and the rows are grouped so a flat column of swatches is not the whole key.
expect(getByText(/never a runtime measurement/i)).toBeInTheDocument();
expect(getByText("Open causes")).toBeInTheDocument();
- expect(getByText("Ringed")).toBeInTheDocument();
+ expect(getByText("No open cause")).toBeInTheDocument();
+ // Radius is a channel under every lens and was captioned in prose only.
+ expect(getByText("lines of code")).toBeInTheDocument();
});
it("MapLegend says it is loading rather than showing bands for absent data", () => {
diff --git a/packages/ui/__tests__/health/file-health-prompt.test.tsx b/packages/ui/__tests__/health/file-health-prompt.test.tsx
new file mode 100644
index 000000000..53ad072e3
--- /dev/null
+++ b/packages/ui/__tests__/health/file-health-prompt.test.tsx
@@ -0,0 +1,199 @@
+/**
+ * The file-level agent prompt, and the drawer chrome that hands it over.
+ *
+ * The prompt is the whole drawer written down, so the things worth pinning are
+ * the ones a reader of the prompt cannot recover if they go missing: the
+ * signals that disagree with the score, the ceilings that make a category
+ * understate itself, and the instruction not to trust any of it blindly.
+ */
+import { describe, it, expect } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import {
+ buildFileHealthAiPrompt,
+ type FileHealthPromptFinding,
+} from "../../src/health/ai-prompt-builder.js";
+import {
+ HealthFileDrawer,
+ type HealthDrawerMetric,
+} from "../../src/health/health-file-drawer.js";
+
+const file = {
+ file_path: "packages/cli/doctor_cmd.py",
+ score: 1.0,
+ nloc: 800,
+ module: "cli",
+ defect_score: 1.0,
+ maintainability_score: 4.2,
+ performance_score: 8.1,
+ has_test_file: false,
+ primary_biomarker: "brain_method",
+ primary_reason: "One function carries most of the command.",
+ total_deduction: 9.0,
+};
+
+function finding(p: Partial<FileHealthPromptFinding> = {}): FileHealthPromptFinding {
+ return {
+ id: "f1",
+ biomarker_type: "brain_method",
+ severity: "high",
+ function_name: "_run_repo_checks",
+ line_start: 120,
+ line_end: 487,
+ health_impact: 3.2,
+ reason: "Oversized, deeply-nested function.",
+ ...p,
+ };
+}
+
+describe("buildFileHealthAiPrompt", () => {
+ it("leads with the file and all three scored dimensions", () => {
+ const out = buildFileHealthAiPrompt({ file, findings: [finding()] });
+ expect(out).toContain("packages/cli/doctor_cmd.py");
+ expect(out).toContain("Defect risk: **1.0/10**");
+ expect(out).toContain("Maintainability: **4.2/10**");
+ expect(out).toContain("Performance: **8.1/10**");
+ });
+
+ it("tells the agent the findings are leads, not instructions", () => {
+ // The whole point of handing over a static report. A prompt that reads as
+ // a work order gets a file edited to satisfy an analyzer.
+ const out = buildFileHealthAiPrompt({ file, findings: [finding()] });
+ expect(out).toMatch(/leads/i);
+ expect(out).toMatch(/false positive/i);
+ expect(out).toMatch(/which findings share a root cause/i);
+ });
+
+ it("says when a category is pinned at its ceiling", () => {
+ // A capped category is a floor on how bad it is, not a measurement, and an
+ // agent that reads the number as exact will under-scope the work.
+ const out = buildFileHealthAiPrompt({
+ file,
+ findings: [finding()],
+ categories: [
+ {
+ category: "complexity",
+ cap: 4,
+ applied_deduction: 4,
+ capped: true,
+ finding_count: 9,
+ },
+ ],
+ });
+ expect(out).toContain("at its ceiling");
+ });
+
+ it("leaves out findings the reader already triaged away", () => {
+ const out = buildFileHealthAiPrompt({
+ file,
+ findings: [
+ finding({ id: "keep", reason: "Still open." }),
+ finding({ id: "gone", status: "false_positive", reason: "Dismissed already." }),
+ finding({ id: "fixed", status: "resolved", reason: "Fixed already." }),
+ ],
+ });
+ expect(out).toContain("Still open.");
+ expect(out).not.toContain("Dismissed already.");
+ expect(out).not.toContain("Fixed already.");
+ });
+
+ it("carries the change signals, which is what the score cannot say", () => {
+ const out = buildFileHealthAiPrompt({
+ file,
+ findings: [finding()],
+ signals: {
+ commit_count_90d: 31,
+ prior_defect_count: 21,
+ bug_magnet: true,
+ last_fix_at: "2026-08-26T10:00:00Z",
+ in_degree: 14,
+ },
+ });
+ expect(out).toContain("31 commits in the last 90 days");
+ expect(out).toContain("bug magnet");
+ expect(out).toContain("2026-08-26");
+ expect(out).toContain("14 files import this one");
+ });
+
+ it("names an untested file as untested", () => {
+ const out = buildFileHealthAiPrompt({ file, findings: [finding()] });
+ expect(out).toMatch(/No test file/i);
+ });
+
+ it("rolls up the long tail instead of printing every finding", () => {
+ const many = Array.from({ length: 18 }, (_, i) =>
+ finding({ id: `f${i}`, health_impact: 3 - i * 0.1, reason: `Reason ${i}` }),
+ );
+ const out = buildFileHealthAiPrompt({ file, findings: many });
+ expect(out).toMatch(/and 8 more lower-impact findings/);
+ // The highest-impact finding is spelled out; the lowest is not.
+ expect(out).toContain("Reason 0");
+ expect(out).not.toContain("Reason 17");
+ });
+
+ it("points the MCP flavor at the tools instead of at a re-read", () => {
+ const generic = buildFileHealthAiPrompt({ file, findings: [finding()] });
+ const mcp = buildFileHealthAiPrompt({
+ file,
+ findings: [finding()],
+ flavor: "claude-code-mcp",
+ });
+ expect(mcp).toContain("get_health(['packages/cli/doctor_cmd.py'])");
+ expect(mcp).toContain("get_risk(['packages/cli/doctor_cmd.py'])");
+ expect(generic).not.toContain("get_health(");
+ });
+});
+
+describe("the drawer's prompt affordance", () => {
+ const m: HealthDrawerMetric = {
+ file_path: "packages/cli/doctor_cmd.py",
+ score: 1.0,
+ max_ccn: 40,
+ max_nesting: 6,
+ nloc: 800,
+ module: "cli",
+ has_test_file: false,
+ };
+
+ it("opens a prompt built from the file the drawer is showing", () => {
+ render(<HealthFileDrawer open onClose={() => {}} metric={m} findings={[]} />);
+ fireEvent.click(screen.getByRole("button", { name: /AI prompt/i }));
+ expect(screen.getByText(/AI prompt for this file/i)).toBeInTheDocument();
+ });
+
+ it("keeps the score breakdown collapsed until asked for", () => {
+ // It is the audit trail for a number stated at the top of the drawer, so
+ // it should not stand between the reader and the findings.
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={m}
+ findings={[]}
+ breakdown={{
+ score: 1,
+ total_deduction: 9,
+ categories: [
+ {
+ category: "complexity",
+ cap: 4,
+ raw_deduction: 6,
+ applied_deduction: 4,
+ capped: true,
+ finding_count: 9,
+ findings: [],
+ },
+ ],
+ }}
+ />,
+ );
+ const toggle = screen.getByRole("button", { name: /Why this score/i });
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ // The hint says what is inside, so collapsing costs no information.
+ expect(toggle.textContent).toContain("−9.00");
+ expect(toggle.textContent).toMatch(/1 category/);
+
+ fireEvent.click(toggle);
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+ expect(screen.getByText(/10\.0 − 9\.00 = 1\.0/)).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/health/map-lens.test.tsx b/packages/ui/__tests__/health/map-lens.test.tsx
index dd2745a03..d7e35b59e 100644
--- a/packages/ui/__tests__/health/map-lens.test.tsx
+++ b/packages/ui/__tests__/health/map-lens.test.tsx
@@ -6,12 +6,12 @@ import { describe, it, expect, vi, beforeAll } from "vitest";
import { render, fireEvent } from "@testing-library/react";
import {
CodeHealthMap,
+ OVERLAY_SPECS,
SEARCH_MARK_CAP,
burdenBand,
performanceBurden,
performanceFill,
- performanceOpacity,
- pressureRing,
+ performanceSentence,
type CodeHealthMapFile,
type MapScope,
} from "../../src/health/code-health-map.js";
@@ -62,9 +62,9 @@ const scope: MapScope = {
describe("burden encoding", () => {
it("bands the count rather than scaling with it", () => {
- // Forty causes and five are the same instruction to the reader. A ring that
- // grew with the raw count would claim a magnitude the analysis has not
- // measured.
+ // Forty causes and five are the same instruction to the reader. An
+ // encoding that grew with the raw count would claim a magnitude the
+ // analysis has not measured.
expect(burdenBand(0)).toBe(0);
expect(burdenBand(1)).toBe(1);
expect([burdenBand(2), burdenBand(4)]).toEqual([2, 2]);
@@ -78,70 +78,74 @@ describe("burden encoding", () => {
performance_analyzed: true,
});
expect(performanceBurden(row).state).toBe("actionable");
- // The one file shape that earns a second mark.
- expect(pressureRing(row)).not.toBeNull();
+ // Named in words, because the field has no channel left to say it in.
+ expect(performanceSentence(row)).toContain("stored plan");
});
- it("rings only a cause with a stored plan, so the mark stays rare", () => {
- const base = { performance_opportunities: 9, performance_analyzed: true } as const;
- expect(
- pressureRing(f("a.py", 10, "core", { ...base, performance_actionability: "advisory" })),
- ).toBeNull();
- expect(
- pressureRing(f("b.py", 10, "core", { ...base, performance_actionability: "investigate" })),
- ).toBeNull();
- });
-
- it("colours the node by how many causes it carries", () => {
+ it("colours the node on the health ramp, with no palette of its own", () => {
const at = (n: number) =>
performanceFill(f("a.py", 10, "core", {
performance_opportunities: n,
performance_analyzed: true,
}));
- expect(at(1)).toContain("--color-caution");
- expect(at(3)).toContain("--color-warning");
- expect(at(9)).toBe("var(--color-error)");
- // The two quiet steps mix toward the page, never toward transparency.
- expect(at(1)).toContain("--color-bg-root");
+ // The same tokens the health lens paints with. An earlier cut mixed its
+ // own tones toward the page, putting colours on this field that exist
+ // nowhere else in the product and going muddy against a dark root.
+ const health = (score: number) => OVERLAY_SPECS.health.fill({ ...f("s.py", 1, null), score });
+ expect(at(1)).toBe(health(7)); // the ramp's fair step
+ expect(at(3)).toBe(health(5)); // poor
+ expect(at(9)).toBe(health(1)); // critical
+ });
+
+ it("never paints a file the healthy green, whatever its state", () => {
+ // Green means healthy on this map and no performance verdict is that: a
+ // cleared file is one with no supported pattern in it, not one measured to
+ // be fast. So the lens uses three of the ramp's four bands.
+ const green = OVERLAY_SPECS.health.fill({ ...f("s.py", 1, null), score: 9 });
+ const fills = [0, 1, 3, 9, 40].map((n) =>
+ performanceFill(f("a.py", 10, "core", { performance_opportunities: n })),
+ );
+ expect(fills).not.toContain(green);
});
- it("pushes a file with no cause into the ground", () => {
- // Most of a repository is this, and the first cut drew every one of them
- // at nine tenths opacity, which tiled into a sheet the marks sat behind.
+ it("gives every file with no open cause the one neutral", () => {
+ // Analyzed-clear and no-detector-for-this-language is a real distinction
+ // and an undecodable one as a second shade of grey. The field says only
+ // "nothing surfaced"; the words carry the rest.
const clear = f("a.py", 10, "core", {
performance_opportunities: 0,
performance_analyzed: true,
});
- const loaded = f("b.py", 10, "core", {
- performance_opportunities: 6,
- performance_actionability: "advisory",
- performance_analyzed: true,
- });
const unsupported = f("c.cc", 10, "core", {
performance_opportunities: 0,
performance_analyzed: false,
});
- expect(performanceOpacity(clear)).toBeLessThan(0.4);
- expect(performanceOpacity(loaded)).toBeGreaterThan(performanceOpacity(clear));
- expect(performanceOpacity(unsupported)).toBeLessThan(performanceOpacity(clear));
+ expect(performanceFill(clear)).toBe(performanceFill(unsupported));
+ expect(performanceSentence(clear)).not.toBe(performanceSentence(unsupported));
+ });
- // A loaded node is fully present whatever its band: the nodes overlap, so
- // a translucent ramp composites two light ones into the darker band's tone.
- const at = (n: number) =>
- performanceOpacity(f("x.py", 10, "core", {
- performance_opportunities: n,
- performance_analyzed: true,
- }));
- expect(at(1)).toBe(at(9));
+ it("spends opacity on focus alone, never on data", () => {
+ const files = [
+ f("core/a.py", 100, "core", { performance_opportunities: 0, performance_analyzed: true }),
+ f("core/b.py", 90, "core", { performance_opportunities: 6, performance_analyzed: true }),
+ ];
+ const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
+ // A lens that also dimmed by burden left a reader unable to tell a quiet
+ // file from one sitting in an unfocused galaxy, and dissolved the field
+ // into a wash by dropping the separating stroke under it.
+ for (const node of container.querySelectorAll("circle[data-path]")) {
+ expect(node.getAttribute("fill-opacity")).toBe("0.9");
+ expect(Number(node.getAttribute("stroke-width"))).toBeGreaterThan(0);
+ }
});
- it("gives an unsupported language no ring and no clear verdict", () => {
+ it("gives an unsupported language no clear verdict", () => {
const row = f("a.cc", 10, "core", {
performance_opportunities: 0,
performance_analyzed: false,
});
- expect(pressureRing(row)).toBeNull();
expect(performanceBurden(row).state).toBe("unsupported");
+ expect(performanceSentence(row)).not.toMatch(/nothing surfaced/i);
});
});
@@ -229,14 +233,23 @@ describe("what the field costs to draw", () => {
}),
);
- it("rings a fraction of the field, not a mark on every node", () => {
- const { container } = render(<CodeHealthMap files={files} overlay="performance" />);
- const nodes = container.querySelectorAll("circle[data-path]").length;
- const rings = container.querySelectorAll("circle[data-ring]").length;
- expect(nodes).toBe(300);
- // The fixture's causes are all advisory, so none earns a ring: the burden
- // rides on the node's own colour and costs no extra element at all.
- expect(rings).toBe(0);
+ it("draws one circle per file and no second mark on top of it", () => {
+ // A rare per-file annotation was tried as a ring outside the node and as a
+ // core inside it. Neither read as belonging to one file on a body this
+ // dense, so the lens spends one channel and the words carry the rest.
+ const planned = files.map((row, i) =>
+ i % 7 === 0 ? { ...row, performance_actionability: "plan_ready" as const } : row,
+ );
+ const { container } = render(<CodeHealthMap files={planned} overlay="performance" />);
+ const nodes = container.querySelectorAll("circle[data-path]");
+ expect(nodes).toHaveLength(300);
+ // Nothing is drawn concentric with a node but smaller or larger than it,
+ // which is the shape both rejected marks had.
+ const centres = new Set([...nodes].map((n) => `${n.getAttribute("cx")},${n.getAttribute("cy")}`));
+ const overlaid = [...container.querySelectorAll("circle:not([data-path])")].filter((c) =>
+ centres.has(`${c.getAttribute("cx")},${c.getAttribute("cy")}`),
+ );
+ expect(overlaid).toHaveLength(0);
});
it("keeps the safeguards that make thousands of nodes affordable", () => {
@@ -246,7 +259,34 @@ describe("what the field costs to draw", () => {
expect(container.querySelectorAll("title")).toHaveLength(0);
expect(container.querySelectorAll("filter")).toHaveLength(0);
expect(container.querySelectorAll("circle[data-path][vector-effect]")).toHaveLength(0);
- expect(container.querySelectorAll("circle[data-ring][vector-effect]")).toHaveLength(0);
+ });
+});
+
+describe("the hover card", () => {
+ const files = [f("core/deep/nested/alpha.py", 120, "core"), f("ui/beta.py", 60, "ui")];
+
+ it("opens at the pointer rather than in a corner of the canvas", () => {
+ // A card pinned to one corner makes every identification a round trip
+ // across the field, and the pointer has usually left the node by the time
+ // the eye gets back.
+ const { container, getByTestId } = render(<CodeHealthMap files={files} />);
+ const node = container.querySelector('circle[data-path="core/deep/nested/alpha.py"]')!;
+ fireEvent.mouseEnter(node, { clientX: 120, clientY: 90 });
+ const card = getByTestId("map-hover-card");
+ expect(card.textContent).toContain("alpha.py");
+ // The directory is present but subordinate: the filename is what is being
+ // pointed at, and it is the last thing a truncated path would show.
+ expect(card.textContent).toContain("core/deep/nested/");
+ expect(card.getAttribute("style")).toMatch(/left:/);
+ });
+
+ it("closes when the pointer leaves the node", () => {
+ const { container, queryByTestId } = render(<CodeHealthMap files={files} />);
+ const node = container.querySelector('circle[data-path="ui/beta.py"]')!;
+ fireEvent.mouseEnter(node, { clientX: 10, clientY: 10 });
+ expect(queryByTestId("map-hover-card")).toBeInTheDocument();
+ fireEvent.mouseLeave(node);
+ expect(queryByTestId("map-hover-card")).not.toBeInTheDocument();
});
});
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index 6b032922b..7686a5b86 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -52,7 +52,7 @@ const FLAVOR_PREAMBLE: Record<AiPromptFlavor, string> = {
* to the repowise tools it already has instead of repeating the exploration
* repowise did at index time; every other flavor keeps the read-first wording.
*/
-type CloserKind = "refactor" | "coverage" | "security" | "hotspot";
+type CloserKind = "refactor" | "coverage" | "security" | "hotspot" | "file-health";
const CLOSER_CONFIG: Record<
CloserKind,
@@ -90,6 +90,14 @@ const CLOSER_CONFIG: Record<
readFirst:
"Start by reading the file end-to-end, then look at what it co-changes with and how well it's tested. High churn is a symptom — the goal is to make this file safer and cheaper to change, not to rewrite it. Don't propose changes until you understand why it churns.",
},
+ "file-health": {
+ mcpSecond: (f) =>
+ `\`get_health(['${f}'])\` for the scored findings behind the numbers below, then \`get_risk(['${f}'])\` for blast radius, co-change partners and test gaps`,
+ mcpInto: "functions the findings name",
+ verb: "change anything",
+ readFirst:
+ "Start by reading the file end-to-end, then its callers, its tests, and whatever it changes alongside. The report above spans several independent signals, and they do not all point at the same fix. Work out which ones share a root cause before you touch anything.",
+ },
};
/**
@@ -1608,3 +1616,319 @@ export function buildRefactoringPlanPrompt({
.filter((s) => s !== "")
.join("\n");
}
+
+// ─────────────────────────────────────────────────────────────────────
+// File health prompt
+// ─────────────────────────────────────────────────────────────────────
+
+/**
+ * Everything the file drawer knows about one file, in the shape the prompt
+ * needs it.
+ *
+ * Structural rather than imported from the drawer, like every other input in
+ * this module: the drawer imports the builder, so importing the drawer's types
+ * back would be a cycle, and a host holding the same facts from somewhere else
+ * can still build the prompt.
+ */
+export interface FileHealthPromptInput {
+ file_path: string;
+ score: number;
+ nloc?: number | null;
+ module?: string | null;
+ defect_score?: number | null;
+ maintainability_score?: number | null;
+ performance_score?: number | null;
+ line_coverage_pct?: number | null;
+ has_test_file?: boolean;
+ duplication_pct?: number | null;
+ max_ccn?: number | null;
+ primary_biomarker?: string | null;
+ primary_reason?: string | null;
+ total_deduction?: number | null;
+}
+
+export interface FileHealthPromptFinding {
+ id: string;
+ biomarker_type: string;
+ severity: string;
+ function_name: string | null;
+ line_start?: number | null;
+ line_end?: number | null;
+ health_impact: number;
+ reason: string;
+ // Spelled with an explicit `undefined` because the drawer forwards rows
+ // whose optional fields are genuinely absent, and the package compiles with
+ // exactOptionalPropertyTypes.
+ status?: string | undefined;
+ details?: Record<string, unknown> | null | undefined;
+}
+
+export interface FileHealthPromptCategory {
+ category: string;
+ cap?: number | null;
+ applied_deduction: number;
+ capped: boolean;
+ finding_count: number;
+}
+
+/** The process and topology facts the drawer's signals panel shows. */
+export interface FileHealthPromptSignals {
+ commit_count_90d?: number | null;
+ change_entropy_pct?: number | null;
+ prior_defect_count?: number | null;
+ bug_magnet?: boolean | null;
+ last_fix_at?: string | null;
+ in_degree?: number | null;
+ out_degree?: number | null;
+ age_days?: number | null;
+}
+
+export interface BuildFileHealthPromptOptions {
+ file: FileHealthPromptInput;
+ findings?: FileHealthPromptFinding[];
+ categories?: FileHealthPromptCategory[];
+ signals?: FileHealthPromptSignals | null;
+ /** Open performance causes, when the host fetched them. */
+ performance?: { items: PerformanceOpportunity[]; total: number } | null;
+ /** Score movement between the last two snapshots, when known. */
+ trendDelta?: number | null;
+ suggestions?: Record<string, string>;
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+/** Spelled out in full; the rest roll up, so a noisy file stays affordable. */
+const MAX_FILE_HEALTH_FINDINGS = 10;
+/** Causes listed by name. Past this, the queue is where to read them. */
+const MAX_FILE_HEALTH_CAUSES = 6;
+
+/**
+ * One file, everything code health has on it, as a prompt.
+ *
+ * Deliberately not `buildAiPrompt`. That one takes a refactoring-queue item
+ * and asks for a refactor. This takes the drawer's own view of a file, which
+ * spans three scored dimensions, the category ceilings, the process and
+ * topology signals, and any open performance causes. Those signals disagree
+ * often enough that the prompt's job is to hand over all of them and ask which
+ * ones share a root cause, rather than to order a fix.
+ */
+export function buildFileHealthAiPrompt({
+ file,
+ findings = [],
+ categories = [],
+ signals,
+ performance,
+ trendDelta,
+ suggestions = {},
+ flavor = "generic",
+ repoName,
+}: BuildFileHealthPromptOptions): string {
+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";
+ // Triaged findings stay on the row. A prompt that asked an agent to fix
+ // something already marked resolved would be reporting the drawer's state
+ // rather than the file's.
+ const open = findings.filter(
+ (f) => f.status !== "resolved" && f.status !== "false_positive",
+ );
+ const ranked = open.slice().sort((a, b) => b.health_impact - a.health_impact);
+ const detailed = ranked.slice(0, MAX_FILE_HEALTH_FINDINGS);
+ const remainder = ranked.slice(MAX_FILE_HEALTH_FINDINGS);
+
+ const pillars = bulletList([
+ file.defect_score != null ? `Defect risk: **${file.defect_score.toFixed(1)}/10**` : null,
+ file.maintainability_score != null
+ ? `Maintainability: **${file.maintainability_score.toFixed(1)}/10**`
+ : null,
+ file.performance_score != null
+ ? `Performance: **${file.performance_score.toFixed(1)}/10**`
+ : null,
+ ]);
+
+ const snapshot = bulletList([
+ `Health score: **${file.score.toFixed(1)}/10** (lower is worse; 10.0 is clean)`,
+ file.total_deduction != null
+ ? `Total deduction: **−${file.total_deduction.toFixed(2)}** across ${categories.length} scoring ${
+ categories.length === 1 ? "category" : "categories"
+ }`
+ : null,
+ trendDelta != null && trendDelta !== 0
+ ? `Score moved ${trendDelta > 0 ? "up" : "down"} ${Math.abs(trendDelta).toFixed(2)} since the previous snapshot`
+ : null,
+ file.nloc != null ? `Size: ${file.nloc} NLOC` : null,
+ file.module ? `Module: \`${file.module}\`` : null,
+ file.max_ccn != null ? `Highest cyclomatic complexity in the file: ${file.max_ccn}` : null,
+ file.duplication_pct != null ? `Duplication: ${file.duplication_pct.toFixed(1)}%` : null,
+ file.line_coverage_pct != null
+ ? `Line coverage: ${Math.round(file.line_coverage_pct)}%`
+ : "Line coverage: not reported",
+ file.has_test_file === false
+ ? "No test file was found for this file, so treat any behaviour change as unverified until you add one."
+ : null,
+ ]);
+
+ const categoryBlock =
+ categories.length > 0
+ ? bulletList(
+ categories
+ .slice()
+ .sort((a, b) => b.applied_deduction - a.applied_deduction)
+ .map((c) => {
+ const label =
+ CATEGORY_LABEL[c.category as keyof typeof CATEGORY_LABEL] ?? c.category;
+ const cap = c.cap != null ? `, capped at −${c.cap.toFixed(1)}` : "";
+ // A capped category understates itself: the raw deductions ran
+ // past the ceiling, so this figure is a floor on how bad it is,
+ // not a measurement of it.
+ const note = c.capped
+ ? " — **at its ceiling**, so this understates the category"
+ : "";
+ return `${label}: −${c.applied_deduction.toFixed(2)} from ${c.finding_count} finding${
+ c.finding_count === 1 ? "" : "s"
+ }${cap}${note}`;
+ }),
+ )
+ : null;
+
+ const findingsBlock = detailed
+ .map((f, i) => {
+ const info = biomarkerInfo(f.biomarker_type);
+ const loc = f.function_name
+ ? `function \`${f.function_name}\`${
+ f.line_start ? ` (line ${f.line_start}${f.line_end ? `–${f.line_end}` : ""})` : ""
+ }`
+ : "file-level";
+ const extra = biomarkerExtraContext(f.biomarker_type, f.details);
+ const suggestion = suggestions[f.biomarker_type];
+ return [
+ `${i + 1}. **${info.label}** · ${CATEGORY_LABEL[info.category]} · ${f.severity.toUpperCase()} · health impact −${f.health_impact.toFixed(2)}`,
+ ` - Where: ${loc}`,
+ ` - Why it's a problem: ${info.description}`,
+ ` - Observed: ${f.reason}`,
+ extra ? ` - Extra context: ${extra}` : null,
+ suggestion ? ` - Suggested direction: ${suggestion}` : null,
+ ]
+ .filter(Boolean)
+ .join("\n");
+ })
+ .join("\n\n");
+
+ const remainderLine = (() => {
+ if (remainder.length === 0) return null;
+ const counts = new Map<string, number>();
+ for (const f of remainder) {
+ counts.set(f.biomarker_type, (counts.get(f.biomarker_type) ?? 0) + 1);
+ }
+ const grouped = Array.from(counts.entries())
+ .sort((a, b) => b[1] - a[1])
+ .map(([type, n]) => `${n}× ${biomarkerInfo(type).label}`)
+ .join(", ");
+ const tail = remainder.reduce((s, f) => s + f.health_impact, 0);
+ return `…and ${remainder.length} more lower-impact finding${
+ remainder.length === 1 ? "" : "s"
+ } (${grouped}; −${tail.toFixed(2)} total). Handle these only after the ranked items above.`;
+ })();
+
+ const signalLines = signals
+ ? bulletList([
+ signals.commit_count_90d != null
+ ? `${signals.commit_count_90d} commits in the last 90 days`
+ : null,
+ signals.change_entropy_pct != null
+ ? `Change entropy ${Math.round(signals.change_entropy_pct)}%, which is how scattered those edits were across the file`
+ : null,
+ signals.prior_defect_count != null && signals.prior_defect_count > 0
+ ? `${signals.prior_defect_count} prior bug fixes have landed here${
+ signals.last_fix_at ? `, most recently ${signals.last_fix_at.slice(0, 10)}` : ""
+ }`
+ : null,
+ signals.bug_magnet
+ ? "Flagged a **bug magnet**: fixes keep landing in this file, so treat a regression here as likely rather than unlucky."
+ : null,
+ signals.in_degree != null
+ ? `${signals.in_degree} file${signals.in_degree === 1 ? "" : "s"} import this one, so changing its public surface reaches all of them`
+ : null,
+ signals.out_degree != null ? `It imports ${signals.out_degree} others` : null,
+ signals.age_days != null ? `First seen ${signals.age_days} days ago` : null,
+ ])
+ : null;
+
+ const causes = performance?.items ?? [];
+ const causeBlock =
+ causes.length > 0
+ ? [
+ bulletList(
+ causes.slice(0, MAX_FILE_HEALTH_CAUSES).map((c) => {
+ // Titled the way every other surface titles a cause: the marker
+ // plus where it fires. The fix's strategy name is not the
+ // cause's name, and using it made distinct causes read as
+ // several copies of one.
+ const first = c.evidence[0];
+ const symbol = c.intervention_symbol ?? first?.function_name ?? null;
+ const at = symbol ? ` in \`${symbol}\`` : "";
+ const line = first?.line_start != null ? ` (line ${first.line_start})` : "";
+ const reach =
+ c.affected_call_sites_total > 1
+ ? ` Reaches ${c.affected_call_sites_total} call sites across ${c.affected_files_total} file${
+ c.affected_files_total === 1 ? "" : "s"
+ }.`
+ : "";
+ const fix = c.fix
+ ? ` Recorded fix: ${c.fix.strategy} (${c.fix.safety}). ${c.fix.rationale}`
+ : "";
+ return `**${biomarkerInfo(c.biomarker_type).label}**${at}${line} — ${c.actionability_reason}${reach}${fix}`;
+ }),
+ ),
+ causes.length > MAX_FILE_HEALTH_CAUSES
+ ? `…and ${causes.length - MAX_FILE_HEALTH_CAUSES} more open on this file.`
+ : null,
+ "These are static reads of the code, not measurements of a running system. Confirm a path is actually hot before optimising it.",
+ ]
+ .filter(Boolean)
+ .join("\n\n")
+ : null;
+
+ const constraints = [
+ "**Read first, edit second.** Read the file, its callers, its tests, and any obvious helpers before proposing a change.",
+ "Group the findings by root cause before you start. Several markers on one function are usually one problem, and fixing them separately produces churn without improving the file.",
+ "Preserve runtime behaviour. No new features, and no opportunistic rewrites in unrelated regions.",
+ "Do **not** change public signatures or exported names unless a verified finding requires it. Call it out explicitly if you must.",
+ "Keep test coverage at least as high as before. If you change logic, add or update tests.",
+ "Match the existing style of the file and its neighbours.",
+ "If a finding turns out to be a false positive once you have read the code, skip it and say why. That is a useful answer, not a failure.",
+ ];
+
+ const expected = [
+ "1. A short triage: which findings share a root cause, which are independent, and which you believe are false positives.",
+ "2. A plan of 3 to 6 bullets for the ones worth acting on, ordered so the riskiest change is not the first.",
+ "3. The edits, scoped to this file plus its tests and any tightly coupled helper.",
+ "4. A summary of what changed, and which specific findings each change should clear.",
+ ];
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ `\n## Target file${repoLine}\n`,
+ `\`${file.file_path}\``,
+ `\n## Current health snapshot\n`,
+ snapshot,
+ pillars ? `\n### Scored dimensions\n\n${pillars}` : "",
+ file.primary_biomarker
+ ? `\n### Leading cause\n\n**${biomarkerInfo(file.primary_biomarker).label}.**${
+ file.primary_reason ? ` ${file.primary_reason}` : ""
+ }`
+ : "",
+ categoryBlock ? `\n## Where the deduction comes from\n\n${categoryBlock}` : "",
+ detailed.length > 0 ? `\n## Open findings (ranked by impact)\n\n${findingsBlock}` : "",
+ remainderLine ? `\n${remainderLine}` : "",
+ causeBlock ? `\n## Open performance causes\n\n${causeBlock}` : "",
+ signalLines ? `\n## How this file behaves over time\n\n${signalLines}` : "",
+ // These carry their own leading blank line, because the filter below that
+ // drops absent sections also drops any bare "" used as a separator.
+ `\n## Hard constraints\n`,
+ bulletList(constraints),
+ `\n## What I expect back\n`,
+ expected.join("\n"),
+ `\n${explorationCloser(flavor, file.file_path, "file-health")}`,
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
diff --git a/packages/ui/src/health/code-health-map.tsx b/packages/ui/src/health/code-health-map.tsx
index 6c2646410..c54af2655 100644
--- a/packages/ui/src/health/code-health-map.tsx
+++ b/packages/ui/src/health/code-health-map.tsx
@@ -15,12 +15,15 @@
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import type { KeyboardEvent as ReactKeyboardEvent } from "react";
+import type {
+ KeyboardEvent as ReactKeyboardEvent,
+ MouseEvent as ReactMouseEvent,
+} from "react";
import { useCommunityFamilies } from "../shared/use-theme-tokens";
import { OVERLAY_ORDER, OVERLAY_SPECS } from "./map/lens";
import { packGalaxies, rand } from "./map/layout";
-import { FileNodes, PressureRings } from "./map/node-layer";
+import { FileNodes } from "./map/node-layer";
import { HoverCard, NodeHighlight, SearchMatches } from "./map/overlay";
import { MapLegendRows, MapLensSwitcher } from "./map/legend";
import type { CodeHealthMapFile, CodeHealthOverlay, FileNode, MapScope } from "./map/types";
@@ -35,7 +38,6 @@ export type {
PerformanceActionability,
} from "./map/types";
export {
- ABSENT_FILL,
NEUTRAL_FILL,
OVERLAY_ORDER,
OVERLAY_SPECS,
@@ -43,9 +45,7 @@ export {
burdenBand,
performanceBurden,
performanceFill,
- performanceOpacity,
performanceSentence,
- pressureRing,
} from "./map/lens";
export type {
LegendRow,
@@ -53,7 +53,6 @@ export type {
PerformanceBurden,
PerformanceBurdenUnit,
PerformanceNodeState,
- PressureRing,
} from "./map/lens";
export { groupByModule, moduleColorId, packGalaxies } from "./map/layout";
export { MapLegend, MapLensSwitcher } from "./map/legend";
@@ -129,6 +128,14 @@ export function CodeHealthMap({
const [dims, setDims] = useState({ width: 0, height: 0 });
const [focusModule, setFocusModule] = useState<string | null>(null);
const [hovered, setHovered] = useState<CodeHealthMapFile | null>(null);
+ // Where the hover card sits, in container-relative px. Tracked only while a
+ // node is hovered: a card that follows the pointer needs the position, and
+ // paying for it across the whole canvas would re-render the facade on every
+ // frame of every sweep that identifies nothing.
+ const [pointer, setPointer] = useState<{ x: number; y: number } | null>(null);
+ const hoveredRef = useRef<CodeHealthMapFile | null>(null);
+ hoveredRef.current = hovered;
+ const moveRaf = useRef<number | null>(null);
// Keyboard cursor. One tab stop reaches the whole field: arrows move over
// modules, Enter descends into one, arrows then move over its files. The
// alternative is a tab stop per node, which is thousands of them.
@@ -152,13 +159,44 @@ export function CodeHealthMap({
keyboardRef.current?.focus();
onSelectRef.current?.(path);
}, []);
- const handleHoverEnter = useCallback((f: CodeHealthMapFile) => {
- setHovered(f);
- onHoverRef.current?.(f);
+ /** Pointer position relative to the container, or null if it has no box. */
+ const localPoint = useCallback((clientX: number, clientY: number) => {
+ const rect = containerRef.current?.getBoundingClientRect();
+ return rect ? { x: clientX - rect.left, y: clientY - rect.top } : null;
}, []);
+ const handleHoverEnter = useCallback(
+ (f: CodeHealthMapFile, e: ReactMouseEvent) => {
+ // Seed the position from the entering event rather than waiting for the
+ // next move, so the card opens where the pointer is instead of wherever
+ // it last was.
+ setPointer(localPoint(e.clientX, e.clientY));
+ setHovered(f);
+ onHoverRef.current?.(f);
+ },
+ [localPoint],
+ );
const handleHoverLeave = useCallback((f: CodeHealthMapFile) => {
setHovered((h) => (h === f ? null : h));
}, []);
+ const handleCanvasMove = useCallback(
+ (e: ReactMouseEvent) => {
+ if (!hoveredRef.current || moveRaf.current != null) return;
+ const { clientX, clientY } = e;
+ // One position per frame. A raw mousemove fires far more often than the
+ // card can be repainted, and each one would be a facade render.
+ moveRaf.current = requestAnimationFrame(() => {
+ moveRaf.current = null;
+ setPointer(localPoint(clientX, clientY));
+ });
+ },
+ [localPoint],
+ );
+ useEffect(
+ () => () => {
+ if (moveRaf.current != null) cancelAnimationFrame(moveRaf.current);
+ },
+ [],
+ );
useEffect(() => {
if (!containerRef.current) return;
@@ -316,6 +354,7 @@ export function CodeHealthMap({
return (
<div
ref={containerRef}
+ onMouseMove={handleCanvasMove}
className="relative w-full overflow-hidden rounded-xl border border-[var(--color-border-default)] focus-within:ring-2 focus-within:ring-[var(--color-accent-primary)]"
style={{ minHeight }}
>
@@ -354,10 +393,15 @@ export function CodeHealthMap({
re-rastered every frame of the transition. A gradient is painted
directly and costs nothing to animate. `currentColor` resolves per
blob, so one def serves every galaxy family. */}
+ {/* The falloff starts early and runs the whole way out. Holding full
+ opacity to seven tenths of the radius and dropping over the last
+ three gave every galaxy a visible disc edge, so the field read as
+ a page of hard circles with files inside them rather than as
+ clouds the files sit in. */}
<radialGradient id="ch-nebula">
<stop offset="0%" stopColor="currentColor" stopOpacity="1" />
- <stop offset="70%" stopColor="currentColor" stopOpacity="1" />
- <stop offset="88%" stopColor="currentColor" stopOpacity="0.55" />
+ <stop offset="40%" stopColor="currentColor" stopOpacity="0.72" />
+ <stop offset="72%" stopColor="currentColor" stopOpacity="0.3" />
<stop offset="100%" stopColor="currentColor" stopOpacity="0" />
</radialGradient>
</defs>
@@ -390,12 +434,13 @@ export function CodeHealthMap({
key={`blob-${g.module}`}
cx={g.cx + offX}
cy={g.cy + offY}
- // Was 0.96 with a blur that spread past the edge; the gradient
- // stops inside its own radius, so the blob grows to compensate.
- r={g.R * 1.02}
+ // The gradient stops inside its own radius, so the blob grows
+ // to compensate; the softer the falloff, the more reach it
+ // needs to end in the page rather than at a rim.
+ r={g.R * 1.1}
style={{ color: fam.hub }}
fill="url(#ch-nebula)"
- fillOpacity={faded ? 0.05 : 0.16}
+ fillOpacity={faded ? 0.04 : 0.13}
data-galaxy={g.module}
className="cursor-zoom-in"
onClick={(e) => {
@@ -430,7 +475,6 @@ export function CodeHealthMap({
galaxies={galaxies}
focusModuleKey={focusGalaxy?.module ?? null}
fill={overlaySpec.fill}
- fillOpacity={overlaySpec.fillOpacity}
offX={offX}
offY={offY}
strokeWidth={0.5 / k}
@@ -440,16 +484,6 @@ export function CodeHealthMap({
onHoverLeave={handleHoverLeave}
/>
- {overlay === "performance" ? (
- <PressureRings
- galaxies={galaxies}
- focusModuleKey={focusGalaxy?.module ?? null}
- offX={offX}
- offY={offY}
- scale={k}
- />
- ) : null}
-
<SearchMatches paths={marked} nodeIndex={nodeIndex} offX={offX} offY={offY} />
<NodeHighlight
@@ -588,7 +622,16 @@ export function CodeHealthMap({
{scope ? <MapScopeNote scope={scope} matches={matches.length} query={q} /> : null}
- {hovered ? <HoverCard file={hovered} overlay={overlay} /> : null}
+ {hovered && pointer ? (
+ <HoverCard
+ file={hovered}
+ overlay={overlay}
+ x={pointer.x}
+ y={pointer.y}
+ width={dims.width}
+ height={dims.height}
+ />
+ ) : null}
</div>
);
}
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 3aaff5c32..89437ef5b 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -16,6 +16,9 @@ import {
} from "./biomarker-glossary";
import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";
import { ScoreBreakdown, type ScoreBreakdownCategory } from "./score-breakdown";
+import { AiPromptButton } from "./ai-prompt-button";
+import { AiPromptModal } from "./ai-prompt-modal";
+import { buildFileHealthAiPrompt } from "./ai-prompt-builder";
import { FileSignalsPanel } from "./file-signals-panel";
import { CollapsibleSection } from "../shared/collapsible-section";
import { formatRelativeTimeOrNull } from "../lib/format";
@@ -116,6 +119,8 @@ export interface HealthFileDrawerProps {
performanceLoading?: boolean;
/** Open one cause on the performance surface. */
onOpportunitySelect?: ((opportunityId: string) => void) | undefined;
+ /** Named in the agent prompt so a pasted prompt says which repo it is for. */
+ repoName?: string;
}
/** Bucket for one-off file-level markers, kept pooled so a file with several
@@ -150,8 +155,10 @@ export function HealthFileDrawer({
performance,
performanceLoading = false,
onOpportunitySelect,
+ repoName,
}: HealthFileDrawerProps) {
const [statusOverride, setStatusOverride] = useState<Record<string, string>>({});
+ const [promptOpen, setPromptOpen] = useState(false);
const [savingId, setSavingId] = useState<string | null>(null);
const setStatus = async (id: string, status: string) => {
if (!onFindingStatusChange) return;
@@ -461,18 +468,25 @@ export function HealthFileDrawer({
</div>
) : null}
- {/* The one action. It was two links to the same page, one a
- tertiary line at the top and one accent-coloured in the
- middle of the body. */}
- {(permalinkHref ?? fileViewHref) ? (
- <a
- href={permalinkHref ?? fileViewHref}
- className="inline-flex w-fit items-center gap-1.5 text-sm font-medium text-[var(--color-accent-primary)] hover:underline"
- >
- <ExternalLink className="h-3.5 w-3.5" />
- Open full page
- </a>
- ) : null}
+ {/* Two actions, and only two: read the whole file's report,
+ or hand what this drawer knows to an agent. The link was
+ once duplicated, a tertiary line at the top and an
+ accent-coloured one in the body, both to the same page. */}
+ <div className="flex flex-wrap items-center gap-3">
+ {(permalinkHref ?? fileViewHref) ? (
+ <a
+ href={permalinkHref ?? fileViewHref}
+ className="inline-flex w-fit items-center gap-1.5 text-sm font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ Open full page
+ </a>
+ ) : null}
+ <AiPromptButton
+ onClick={() => setPromptOpen(true)}
+ label="AI prompt"
+ />
+ </div>
</div>
</div>
@@ -493,17 +507,24 @@ export function HealthFileDrawer({
<BugHistorySection signals={signals} />
+ {/* Collapsed by default. This is the audit trail for a number
+ the drawer already states at the top, beside a leading cause
+ that names the biggest contributor in words. A reader who
+ wants the per-category arithmetic can ask for it; one who
+ does not should not scroll past it to reach the findings. */}
{breakdown ? (
- <section className="flex flex-col gap-2">
- <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Why this score
- </h3>
+ <CollapsibleSection
+ title="Why this score"
+ hint={`−${breakdown.total_deduction.toFixed(2)} across ${
+ breakdown.categories.length
+ } ${breakdown.categories.length === 1 ? "category" : "categories"}`}
+ >
<ScoreBreakdown
score={breakdown.score}
totalDeduction={breakdown.total_deduction}
categories={breakdown.categories}
/>
- </section>
+ </CollapsibleSection>
) : null}
{findings.length > 0 ? (
@@ -536,6 +557,39 @@ export function HealthFileDrawer({
</>
)}
</div>
+
+ {/* Everything the drawer knows about this file, as one prompt. The
+ modal renders through a portal, so it sits here for locality
+ rather than for layout. */}
+ <AiPromptModal
+ open={promptOpen}
+ onOpenChange={setPromptOpen}
+ filePath={metric?.file_path ?? null}
+ title="AI prompt for this file"
+ description="Every scored finding, category ceiling, open performance cause and change signal this drawer holds, written up so an agent can triage the file before it edits anything."
+ getPrompt={
+ metric
+ ? (flavor) =>
+ buildFileHealthAiPrompt({
+ file: metric,
+ findings: findings.map((f) => ({
+ ...f,
+ // Triage applied in this session but not yet refetched,
+ // so a finding just marked resolved leaves the prompt.
+ status: statusOverride[f.id] ?? f.status,
+ details: f.details as Record<string, unknown> | null | undefined,
+ })),
+ categories: breakdown?.categories ?? [],
+ signals: signals ?? null,
+ performance: performance ?? null,
+ trendDelta: trend?.delta ?? null,
+ suggestions,
+ flavor,
+ ...(repoName ? { repoName } : {}),
+ })
+ : null
+ }
+ />
</AdaptivePanel>
);
}
diff --git a/packages/ui/src/health/impact-figure.tsx b/packages/ui/src/health/impact-figure.tsx
index 59d761948..d38f4d63c 100644
--- a/packages/ui/src/health/impact-figure.tsx
+++ b/packages/ui/src/health/impact-figure.tsx
@@ -13,9 +13,19 @@ import { formatHealthImpact } from "./tokens";
*/
export function ImpactFigure({
impact,
+ tone = "deduction",
className,
}: {
impact: number | null | undefined;
+ /**
+ * How loud the figure is.
+ *
+ * `deduction` is the red, for a figure that is the point of its row.
+ * `muted` is for a long list of them, where every row already carries a
+ * severity mark and colouring the numbers too turns a breakdown into a wall
+ * of red that ranks nothing.
+ */
+ tone?: "deduction" | "muted";
className?: string;
}) {
const figure = formatHealthImpact(impact);
@@ -27,7 +37,13 @@ export function ImpactFigure({
);
}
return (
- <span className={cn("shrink-0 tabular-nums text-[var(--color-error)]", className)}>
+ <span
+ className={cn(
+ "shrink-0 tabular-nums",
+ tone === "muted" ? "text-[var(--color-text-tertiary)]" : "text-[var(--color-error)]",
+ className,
+ )}
+ >
{figure}
</span>
);
diff --git a/packages/ui/src/health/map/inspector.tsx b/packages/ui/src/health/map/inspector.tsx
index 616237fc2..a215cbf4b 100644
--- a/packages/ui/src/health/map/inspector.tsx
+++ b/packages/ui/src/health/map/inspector.tsx
@@ -17,20 +17,12 @@ import { cn } from "../../lib/cn";
import { scoreBadgeClass } from "../tokens";
import {
PERFORMANCE_STATE_LABEL,
- burdenBand,
performanceBurden,
+ performanceFill,
performanceSentence,
} from "./lens";
import type { CodeHealthMapFile, CodeHealthOverlay, MapScope } from "./types";
-/** The ring's colour per band, so the inspector's mark matches the canvas. */
-const RING_TONE: Record<0 | 1 | 2 | 3, string> = {
- 0: "var(--color-border-default)",
- 1: "var(--color-caution)",
- 2: "var(--color-warning)",
- 3: "var(--color-error)",
-};
-
/** Rows the ranked list draws. Past this it is an inventory, not a lead. */
export const FIELD_LIST_CAP = 50;
@@ -201,16 +193,16 @@ export function MapInspector({
<div className="flex items-center gap-2">
{/* The lens decides what leads. Under performance the defect score is
not the subject, and putting its coloured badge first told the
- reader the file was fine while the ring beside it said otherwise. */}
+ reader the file was fine while the mark beside it said otherwise.
+
+ The mark is the node as the canvas draws it, from the same
+ function, so the selection and the field it was picked out of can
+ never describe the file differently. */}
{overlay === "performance" ? (
<span
aria-hidden
className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full"
- style={{
- border: `2px ${burden.state === "actionable" ? "solid" : "dashed"} ${
- burden.count > 0 ? RING_TONE[burdenBand(burden.count)] : "var(--color-border-default)"
- }`,
- }}
+ style={{ backgroundColor: performanceFill(file) }}
/>
) : (
<span
diff --git a/packages/ui/src/health/map/legend.tsx b/packages/ui/src/health/map/legend.tsx
index 10e1d9c1d..640f807bb 100644
--- a/packages/ui/src/health/map/legend.tsx
+++ b/packages/ui/src/health/map/legend.tsx
@@ -14,21 +14,8 @@ import type { KeyboardEvent as ReactKeyboardEvent } from "react";
import { OVERLAY_ORDER, OVERLAY_SPECS, type LegendRow, type OverlaySpec } from "./lens";
import type { CodeHealthOverlay } from "./types";
-/** One key swatch: a disc for a fill, an outline for a ring. */
+/** One key swatch: a disc in the row's fill. */
function Swatch({ row, size }: { row: LegendRow; size: number }) {
- if (row.mark === "ring") {
- return (
- <span
- aria-hidden
- className="inline-block shrink-0 rounded-full"
- style={{
- width: size,
- height: size,
- border: `1.5px ${row.dash ? "dashed" : "solid"} ${row.fill}`,
- }}
- />
- );
- }
return (
<span
aria-hidden
@@ -38,6 +25,25 @@ function Swatch({ row, size }: { row: LegendRow; size: number }) {
);
}
+/**
+ * The one channel every lens shares, keyed once.
+ *
+ * A node's radius is its line count under all of them, and until now that was
+ * stated only in prose in a caption. Two discs and a label is what a reader
+ * can actually match against the field.
+ */
+function SizeKey({ className }: { className?: string }) {
+ return (
+ <span className={`flex items-center gap-1.5 ${className ?? ""}`}>
+ <span aria-hidden className="flex items-end gap-0.5">
+ <span className="inline-block h-1 w-1 rounded-full bg-[var(--color-text-tertiary)]" />
+ <span className="inline-block h-2.5 w-2.5 rounded-full bg-[var(--color-text-tertiary)]" />
+ </span>
+ lines of code
+ </span>
+ );
+}
+
/** The active lens's key rows, shared by both placements. */
export function MapLegendRows({ spec, loading }: { spec: OverlaySpec; loading: boolean }) {
if (loading) {
@@ -63,6 +69,10 @@ export function MapLegendRows({ spec, loading }: { spec: OverlaySpec; loading: b
</span>
</Fragment>
))}
+ <span className="mt-1 font-mono text-[9px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Size
+ </span>
+ <SizeKey className="text-[var(--color-text-tertiary)]" />
</div>
);
}
@@ -169,6 +179,7 @@ export function MapLegend({
</Fragment>
))
)}
+ {loading ? null : <SizeKey />}
<span className="font-mono text-[10px] uppercase tracking-[0.12em]">{spec.caption}</span>
</div>
);
diff --git a/packages/ui/src/health/map/lens.ts b/packages/ui/src/health/map/lens.ts
index 7b462ceea..fb8b3e701 100644
--- a/packages/ui/src/health/map/lens.ts
+++ b/packages/ui/src/health/map/lens.ts
@@ -8,12 +8,20 @@
import { scoreBand, type ScoreBand } from "../tokens";
import type { CodeHealthMapFile, CodeHealthOverlay, PerformanceActionability } from "./types";
-/* Band -> SVG fill var(). The same ramp as every score pill on the surface. */
+/**
+ * Band -> SVG fill var().
+ *
+ * The canvas ramp, not the semantic ink the score pills use. Those are tuned
+ * to be read as small coloured type against the page; this field is thousands
+ * of overlapping filled discs, which is a different job in both themes. The
+ * two ramps are the same four severity steps in the same hue family and are
+ * deliberately not the same values. See `--color-node-*` in globals.css.
+ */
const BAND_FILL: Record<ScoreBand, string> = {
- critical: "var(--color-error)",
- poor: "var(--color-warning)",
- fair: "var(--color-caution)",
- good: "var(--color-success)",
+ critical: "var(--color-node-critical)",
+ poor: "var(--color-node-poor)",
+ fair: "var(--color-node-fair)",
+ good: "var(--color-node-good)",
};
const BAND_LABEL: { band: ScoreBand; label: string }[] = [
@@ -23,27 +31,23 @@ const BAND_LABEL: { band: ScoreBand; label: string }[] = [
{ band: "good", label: "Healthy" },
];
-/** Neutral fill for nodes a non-health lens has no signal for. */
-export const NEUTRAL_FILL = "var(--color-text-tertiary)";
-
-/** Quieter still: the file was never looked at, which is not "no signal". */
-export const ABSENT_FILL = "var(--color-border-default)";
+/**
+ * Neutral fill for nodes a lens has no signal for.
+ *
+ * On a field of thousands this is most of what a reader sees, so it has to sit
+ * close enough to the background to read as ground. It is a token rather than
+ * a mix of one, because how far toward the page it has to sit is not the same
+ * against near-black as against cream.
+ */
+export const NEUTRAL_FILL = "var(--color-node-neutral)";
export interface LegendRow {
fill: string;
label: string;
/**
- * How the swatch is drawn. `ring` is an outline rather than a disc, so the
- * performance key reads as the mark it describes; `dash` mirrors the ring's
- * stroke pattern, which is the lens's non-colour channel.
- */
- mark?: "dot" | "ring";
- dash?: string;
- /**
- * Which channel this row belongs to. The performance lens marks a node on
- * two independent axes, and a flat list of swatches gives a reader no way to
- * see that the first three are one axis and the next three another. The key
- * prints the group once, where it changes.
+ * Which channel this row belongs to. The key prints the group once, where it
+ * changes, so a column of swatches reads as the axes it describes rather
+ * than as one flat list.
*/
group?: string;
}
@@ -54,8 +58,6 @@ export interface OverlaySpec {
/** Caption shown under the legend key. */
caption: string;
fill: (f: CodeHealthMapFile) => string;
- /** Per-node opacity, when the lens needs most of the field to sit back. */
- fillOpacity?: (f: CodeHealthMapFile) => number;
legend: LegendRow[];
}
@@ -86,24 +88,27 @@ function churnFill(pctile: number | null | undefined): string {
/* ------------------------------------------------------------------ *
* Performance lens
*
- * One mark on the node, one mark beside it, and a field that gets out of
- * the way.
+ * The health ramp with its top step removed.
*
- * A file a detector cleared is a file with no *supported pattern* in it, not a
- * file measured to be fast, so it is never painted the healthy green. But most
- * of a repository is that, and the first cut of this lens gave every one of
- * those files a solid mid-grey disc at nine-tenths opacity. Two thousand of
- * them tiled into an opaque sheet: node boundaries vanished, and an outline
- * drawn around one large node read as a lasso thrown over a crowd of small
- * ones. The burden also rode on that outline, in a colour and a dash pattern,
- * which at four-pixel radius is a handful of disconnected specks.
+ * This lens is a sibling of the health lens, not a different chart, so it
+ * paints with the same four-band ramp, at the same flat opacity, over the same
+ * geometry. It uses three of the four bands. A file a detector cleared is a
+ * file with no supported pattern in it, not a file measured to be fast, and on
+ * this map green means healthy; so performance has no green, and that single
+ * rule is the whole difference between the two lenses.
*
- * So the quiet files recede to a faint substrate, and colour moves onto the
- * node, where the eye already is: how many open causes, in three steps. The
- * outline survives for the one thing worth a second mark, a cause with a
- * stored plan, and is a plain bright ring rather than a fourth hue. Advisory
- * and investigate are named in words by the hover card, the inspector and the
- * ranked list, which is where a distinction this fine belongs.
+ * An earlier cut said the same thing with its own palette and its own opacity
+ * ramp: bands mixed toward the page, quiet files at a fraction of an alpha,
+ * and no separating stroke under them. Three channels carrying one variable
+ * produced tones that exist nowhere else in the product, went muddy against a
+ * dark root, and dissolved the arrangement into a haze in which a ring around
+ * one node read as a lasso thrown over its neighbours.
+ *
+ * The node's colour is the lens's only channel. Actionability - advisory,
+ * investigate, or a cause with a stored plan - is named in words by the hover
+ * card, the inspector and the ranked list. It had a mark of its own on the
+ * field, and on a body of thousands of small packed discs no second mark reads
+ * as belonging to one file rather than to the cluster around it.
* ------------------------------------------------------------------ */
export type PerformanceNodeState =
@@ -114,7 +119,7 @@ export type PerformanceNodeState =
| "unsupported"
| "unknown";
-/** Which unit the ring is counting, so the copy can say so. */
+/** Which unit the burden is counted in, so the copy can say so. */
export type PerformanceBurdenUnit = "opportunities" | "observations";
export interface PerformanceBurden {
@@ -169,27 +174,18 @@ export function performanceBurden(f: CodeHealthMapFile): PerformanceBurden {
};
}
-/** Fill: how many open causes, or a quiet neutral. Never the healthy green. */
-export function performanceFill(f: CodeHealthMapFile): string {
- const { state, count } = performanceBurden(f);
- const band = burdenBand(count);
- if (band !== 0) return BAND_TONE[band];
- return state === "unsupported" || state === "unknown" ? ABSENT_FILL : NEUTRAL_FILL;
-}
-
/**
- * How present a node is.
+ * Fill: how many open causes, on the health ramp, or the quiet neutral.
*
- * A few hundred files out of thousands carry a cause, so the rest sit back far
- * enough for those to read as figure rather than as more of the ground. A
- * loaded node is fully present, and its band is carried by the tone: a single
- * cause is by far the commonest of the three, so the ramp has to quieten it
- * without making it transparent.
+ * Files with no open cause all take one fill. Whether a detector cleared the
+ * file or has no support for its language is a real distinction, but it is one
+ * no reader can decode from a second shade of grey, so it is carried by
+ * {@link performanceSentence} instead. Coverage and dead code already collapse
+ * their own version of it the same way.
*/
-export function performanceOpacity(f: CodeHealthMapFile): number {
- const { state, count } = performanceBurden(f);
- if (burdenBand(count) !== 0) return 1;
- return state === "unsupported" || state === "unknown" ? 0.14 : 0.26;
+export function performanceFill(f: CodeHealthMapFile): string {
+ const band = burdenBand(performanceBurden(f).count);
+ return band === 0 ? NEUTRAL_FILL : BURDEN_FILL[band];
}
/** Burden band, 0 when the file carries none. Bounded so 40 causes is a step. */
@@ -201,38 +197,18 @@ export function burdenBand(count: number): 0 | 1 | 2 | 3 {
}
/**
- * The three steps, quietened toward the page rather than toward transparency.
+ * The three steps, borrowed whole from the health ramp.
*
- * The nodes overlap by construction, so a translucent ramp is read wrong: two
- * overlapping one-cause files composite into exactly the tone that means two
- * to four. Mixing into the background instead keeps every node opaque, so a
- * colour on this field always means one band and never a pile of them.
+ * Same tokens the score pills and the health lens use, so a colour means the
+ * same severity wherever it appears on this surface. `BAND_FILL.good` is
+ * deliberately absent: it is the only band that would claim a file is fine.
*/
-const BAND_TONE: Record<1 | 2 | 3, string> = {
- 1: "color-mix(in srgb, var(--color-caution) 60%, var(--color-bg-root))",
- 2: "color-mix(in srgb, var(--color-warning) 82%, var(--color-bg-root))",
- 3: "var(--color-error)",
+const BURDEN_FILL: Record<1 | 2 | 3, string> = {
+ 1: BAND_FILL.fair,
+ 2: BAND_FILL.poor,
+ 3: BAND_FILL.critical,
};
-export interface PressureRing {
- stroke: string;
- /** Stroke width in user units, before the caller divides by the zoom scale. */
- width: number;
-}
-
-/**
- * The ring for one row, or `null`, which is most of them.
- *
- * Only a cause with a stored plan takes one: 29 of 768 here. A mark every
- * coloured node carries is not a mark, and a plain bright ring reads as
- * "singled out" without competing with the colour underneath it for the same
- * meaning.
- */
-export function pressureRing(f: CodeHealthMapFile): PressureRing | null {
- if (performanceBurden(f).state !== "actionable") return null;
- return { stroke: "var(--color-text-primary)", width: 1.1 };
-}
-
export const PERFORMANCE_STATE_LABEL: Record<PerformanceNodeState, string> = {
actionable: "Stored plan",
advisory: "Advisory",
@@ -270,17 +246,13 @@ export const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {
},
performance: {
label: "Performance",
- caption:
- "galaxy = module · dot = file, sized by lines of code · colour = open causes, never a runtime measurement",
+ caption: "colour = open causes, never a runtime measurement · no green: nothing here is proven fast",
fill: performanceFill,
- fillOpacity: performanceOpacity,
legend: [
- { group: "Open causes", fill: BAND_TONE[3], label: "5 or more" },
- { group: "Open causes", fill: BAND_TONE[2], label: "2 to 4" },
- { group: "Open causes", fill: BAND_TONE[1], label: "1" },
- { group: "Ringed", fill: "var(--color-text-primary)", label: "Stored plan", mark: "ring" },
- { group: "No cause", fill: NEUTRAL_FILL, label: "Analyzed, nothing surfaced" },
- { group: "No cause", fill: ABSENT_FILL, label: "Not analyzed" },
+ { group: "Open causes", fill: BURDEN_FILL[3], label: "5 or more" },
+ { group: "Open causes", fill: BURDEN_FILL[2], label: "2 to 4" },
+ { group: "Open causes", fill: BURDEN_FILL[1], label: "1" },
+ { group: "No open cause", fill: NEUTRAL_FILL, label: "Nothing surfaced" },
],
},
coverage: {
diff --git a/packages/ui/src/health/map/node-layer.tsx b/packages/ui/src/health/map/node-layer.tsx
index 91dd777c9..c21ffe298 100644
--- a/packages/ui/src/health/map/node-layer.tsx
+++ b/packages/ui/src/health/map/node-layer.tsx
@@ -1,23 +1,28 @@
"use client";
/**
- * The base field: one circle per file, and the performance lens's rings.
+ * The base field: one circle per file, and nothing else.
*
- * Both layers are memoized and fed only stable props, so hover, selection and
- * search - which all re-render the facade - never reconcile these elements.
+ * Memoized and fed only stable props, so hover, selection and search - which
+ * all re-render the facade - never reconcile these thousands of elements.
* Everything that moves with the pointer lives in the overlay layer instead.
+ *
+ * There is deliberately no second mark layer here. A rare per-file annotation
+ * was tried both ways, as a ring outside the node and as a core inside it, and
+ * neither survived contact with the field: at this density an outline lands on
+ * the neighbours and reads as a mark on the group, and a core in the one
+ * colour with enough contrast to be seen is louder than the severity ramp it
+ * is annotating. Anything that fine belongs in the words beside the map.
*/
import { memo } from "react";
-import { pressureRing } from "./lens";
+import type { MouseEvent as ReactMouseEvent } from "react";
import type { CodeHealthMapFile, Galaxy } from "./types";
export interface NodeLayerProps {
galaxies: Galaxy[];
focusModuleKey: string | null;
fill: (f: CodeHealthMapFile) => string;
- /** Per-node opacity, so a lens can push most of the field into the ground. */
- fillOpacity?: ((f: CodeHealthMapFile) => number) | undefined;
offX: number;
offY: number;
/**
@@ -36,7 +41,8 @@ export interface NodeLayerProps {
strokeWidth: number;
interactive: boolean;
onSelect: (path: string) => void;
- onHoverEnter: (f: CodeHealthMapFile) => void;
+ /** The event comes along so the hover card can open at the pointer. */
+ onHoverEnter: (f: CodeHealthMapFile, e: ReactMouseEvent) => void;
onHoverLeave: (f: CodeHealthMapFile) => void;
}
@@ -44,7 +50,6 @@ export const FileNodes = memo(function FileNodes({
galaxies,
focusModuleKey,
fill,
- fillOpacity,
offX,
offY,
strokeWidth,
@@ -74,16 +79,18 @@ export const FileNodes = memo(function FileNodes({
cy={nd.y + offY}
r={nd.r}
fill={fill(f)}
- fillOpacity={
- faded ? 0.18 : ((fillOpacity?.(f) ?? 0.9) as number)
- }
+ // One opacity for every lens. Opacity here means "this galaxy
+ // is not the focused one" and nothing else; a lens that also
+ // spent it on data left the reader unable to tell a quiet
+ // file from a dimmed one.
+ fillOpacity={faded ? 0.18 : 0.9}
+ // The separating stroke is what makes this a field of files
+ // rather than a wash. Every node keeps it, whatever it is
+ // filled with.
stroke="var(--color-bg-root)"
- // A quiet node keeps no separating stroke: at a tenth of the
- // field's opacity the stroke is louder than the node, which
- // turns a soft substrate back into a grid of rings.
- strokeWidth={(fillOpacity?.(f) ?? 0.9) < 0.4 ? 0 : strokeWidth}
+ strokeWidth={strokeWidth}
className={interactive ? "cursor-pointer" : undefined}
- onMouseEnter={() => onHoverEnter(f)}
+ onMouseEnter={(e) => onHoverEnter(f, e)}
onMouseLeave={() => onHoverLeave(f)}
onClick={(e) => {
e.stopPropagation();
@@ -98,57 +105,3 @@ export const FileNodes = memo(function FileNodes({
</>
);
});
-
-/**
- * The one extra mark, as its own layer.
- *
- * Only a cause with a stored plan takes a ring, so this draws tens of elements
- * where the node layer draws thousands. The burden itself is the node's
- * colour; this says "and there is something written down for this one".
- */
-export const PressureRings = memo(function PressureRings({
- galaxies,
- focusModuleKey,
- offX,
- offY,
- scale,
-}: {
- galaxies: Galaxy[];
- focusModuleKey: string | null;
- offX: number;
- offY: number;
- /** Zoom scale, so stroke widths land where they were designed. */
- scale: number;
-}) {
- return (
- <g className="pointer-events-none">
- {galaxies.map((g) => {
- const faded = focusModuleKey != null && g.module !== focusModuleKey;
- return (
- <g key={`rings-${g.module}`} opacity={faded ? 0.2 : 1}>
- {g.nodes.map((nd) => {
- const ring = pressureRing(nd.file);
- if (!ring) return null;
- const width = ring.width / scale;
- return (
- <circle
- key={nd.file.file_path}
- data-ring={nd.file.file_path}
- cx={nd.x + offX}
- cy={nd.y + offY}
- // Outside the node, by half the stroke plus a hairline, so
- // the ring reads as pressure around the file rather than as
- // a border on it.
- r={nd.r + width}
- fill="none"
- stroke={ring.stroke}
- strokeWidth={width}
- />
- );
- })}
- </g>
- );
- })}
- </g>
- );
-});
diff --git a/packages/ui/src/health/map/overlay.tsx b/packages/ui/src/health/map/overlay.tsx
index 08e6c9414..7e068e453 100644
--- a/packages/ui/src/health/map/overlay.tsx
+++ b/packages/ui/src/health/map/overlay.tsx
@@ -108,31 +108,75 @@ export function SearchMatches({
}
/**
- * Pointer-bound decoding, in the active lens's terms.
+ * Card box, for the edge flip.
+ *
+ * Approximate on purpose: the card sizes to its content, and this only has to
+ * decide which side of the pointer it opens on.
+ */
+const CARD_W = 300;
+const CARD_H = 84;
+/** Gap between the pointer and the card, so the cursor never sits on it. */
+const CARD_GAP = 16;
+
+/**
+ * Pointer-bound decoding, in the active lens's terms, at the pointer.
*
* Hover answers "what is this and what does the current lens say about it".
* The lens's own sentence leads, so the card and the inspector describe the
* same object the same way.
+ *
+ * It follows the cursor rather than sitting in a corner. On a field of
+ * thousands of nodes a fixed card makes every identification a round trip
+ * across the canvas and back, and by the time the eye returns the pointer has
+ * usually left the node it was asking about. The card flips to the other side
+ * of the pointer near an edge so it is never clipped by the container.
*/
export function HoverCard({
file,
overlay,
+ x,
+ y,
+ width,
+ height,
}: {
file: CodeHealthMapFile;
overlay: CodeHealthOverlay;
+ /** Pointer position, in container-relative px. */
+ x: number;
+ y: number;
+ width: number;
+ height: number;
}) {
const cov = file.line_coverage_pct;
+ const slash = file.file_path.lastIndexOf("/");
+ const dir = slash < 0 ? "" : file.file_path.slice(0, slash + 1);
+ const name = slash < 0 ? file.file_path : file.file_path.slice(slash + 1);
+ const left = x + CARD_GAP + CARD_W > width ? x - CARD_GAP - CARD_W : x + CARD_GAP;
+ const top = y + CARD_GAP + CARD_H > height ? y - CARD_GAP - CARD_H : y + CARD_GAP;
return (
- <div className="pointer-events-none absolute bottom-3 left-3 max-w-[75%] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1.5 text-xs shadow-md">
- <div className="truncate font-mono text-[var(--color-text-primary)]">
- {file.file_path}
+ <div
+ data-testid="map-hover-card"
+ // Sized to its content up to a ceiling, so a short name gets a small
+ // card. The name is the answer to "what am I pointing at" and is never
+ // truncated: it wraps instead, and the directory above it is the part
+ // that gives way when the path is long.
+ className="pointer-events-none absolute z-20 w-max max-w-[300px] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1.5 shadow-md"
+ style={{ left: Math.max(0, left), top: Math.max(0, top) }}
+ >
+ {dir ? (
+ <div className="truncate font-mono text-[10px] leading-tight text-[var(--color-text-tertiary)]">
+ {dir}
+ </div>
+ ) : null}
+ <div className="break-all font-mono text-[11px] font-medium leading-snug text-[var(--color-text-primary)]">
+ {name}
</div>
{overlay === "performance" ? (
- <div className="text-[var(--color-text-secondary)]">
+ <div className="mt-0.5 text-[11px] leading-tight text-[var(--color-text-secondary)]">
{performanceSentence(file)}
</div>
) : null}
- <div className="text-[var(--color-text-tertiary)] tabular-nums">
+ <div className="mt-0.5 text-[10px] leading-tight text-[var(--color-text-tertiary)] tabular-nums">
score {file.score.toFixed(1)} · {file.nloc.toLocaleString()} NLOC
{cov != null ? ` · ${Math.round(cov)}% cov` : ""}
{file.has_test_file ? "" : " · untested"}
diff --git a/packages/ui/src/health/score-breakdown.tsx b/packages/ui/src/health/score-breakdown.tsx
index 535863c95..de18e14bf 100644
--- a/packages/ui/src/health/score-breakdown.tsx
+++ b/packages/ui/src/health/score-breakdown.tsx
@@ -4,10 +4,24 @@ import {
biomarkerLabel,
type BiomarkerCategory,
} from "./biomarker-glossary";
-import { scoreBadgeClass, type Severity } from "./tokens";
+import { type Severity } from "./tokens";
import { ImpactFigure } from "./impact-figure";
import { SeverityMark } from "./severity-mark";
+/**
+ * The proportion bars carry no colour.
+ *
+ * They were all the deduction red, which on a file with seven scoring
+ * categories is seven red bars: the colour said "bad" seven times and ranked
+ * nothing. Nothing was gained by tying the tone to severity either, because
+ * the bar's own length already is the magnitude and the rows are sorted by it.
+ * So the bar states one thing, in one channel, and the red is left to mean
+ * something where it is still used.
+ */
+const BAR_FILL = "color-mix(in srgb, var(--color-text-tertiary) 55%, transparent)";
+/** Fainter again when there is no cap, so the bar's scale is approximate. */
+const BAR_FILL_UNCAPPED = "color-mix(in srgb, var(--color-text-tertiary) 30%, transparent)";
+
export interface ScoreBreakdownCategoryFinding {
id: string;
biomarker_type: string;
@@ -44,17 +58,13 @@ export function ScoreBreakdown({
}: ScoreBreakdownProps) {
return (
<div className="space-y-3">
- <div className="flex items-baseline gap-3">
- <span
- className={`inline-flex items-center rounded-md px-2 py-1 text-lg font-bold tabular-nums ${scoreBadgeClass(score)}`}
- >
- {score.toFixed(1)}
- <span className="ml-0.5 text-xs font-normal opacity-70">/10</span>
- </span>
- <span className="text-xs text-[var(--color-text-tertiary)]">
- 10.0 − {totalDeduction.toFixed(2)} = {score.toFixed(2)}
- </span>
- </div>
+ {/* The arithmetic, once, quietly. This led with the score again as a
+ large coloured badge, a second copy of the figure the surface above
+ it already shows at four times the size. What this section is for is
+ the subtraction, not the total. */}
+ <p className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ 10.0 − {totalDeduction.toFixed(2)} = {score.toFixed(1)}
+ </p>
<div className="space-y-2.5">
{[...categories]
@@ -105,17 +115,16 @@ export function ScoreBreakdown({
</div>
<div className="mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
<div
- className={
- cap != null
- ? "h-full bg-[var(--color-error)]/70"
- : "h-full bg-[var(--color-text-tertiary)]/40"
- }
+ className="h-full"
title={
cap == null
? "No defined cap for this category — bar scale is approximate."
: undefined
}
- style={{ width: `${pct}%` }}
+ style={{
+ width: `${pct}%`,
+ background: cap == null ? BAR_FILL_UNCAPPED : BAR_FILL,
+ }}
/>
</div>
{c.findings.length > 0 && (
@@ -134,7 +143,10 @@ export function ScoreBreakdown({
{f.function_name}
</span>
) : null}
- <ImpactFigure impact={f.applied_impact} className="ml-auto" />
+ {/* Muted: the severity mark at the head of the row is
+ already the colour channel, and six red numbers under
+ a red bar rank nothing. */}
+ <ImpactFigure impact={f.applied_impact} tone="muted" className="ml-auto" />
</li>
))}
{c.findings.length > 6 ? (
diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.css
index bfc9d62ed..e4a4dc238 100644
--- a/packages/ui/styles/globals.css
+++ b/packages/ui/styles/globals.css
@@ -126,6 +126,30 @@
--color-info: #3f6ea5; /* muted blue — distinct from the plum accent-secondary */
--color-caution: #a8821f; /* between warning and success; medium severity / fair score band */
+ /* Canvas node ramp — the severity ramp as FILL, for the health galaxy's
+ thousands of overlapping discs.
+
+ The semantic vars above are ink: tuned to stay readable as small coloured
+ type against the page. That is a different job, and used as fill they fail
+ differently in each theme. Against the dark root the ink has to be high
+ luminance, so a field of it is emissive rather than printed. Against this
+ cream root `warning` and `caution` land at nearly the same hue and
+ lightness: harmless when the two are never adjacent as type, fatal as
+ neighbouring bands, where it erased the middle of the ramp.
+
+ Same red / amber / gold / green family, chroma and value pulled back
+ together, and the amber and gold steps separated by hue as well as
+ lightness. Fill only: pills, badges and text keep the ink vars, so the
+ map's red is deliberately not byte-identical to the pill's. */
+ --color-node-critical: #9e3226;
+ --color-node-poor: #ad5a19;
+ --color-node-fair: #b3872a;
+ --color-node-good: #2a7a54;
+ /* No signal under the active lens. This was mixed a third of the way toward
+ the root, which recedes correctly against near-black and washes out to a
+ ghost against cream. One value cannot serve both directions. */
+ --color-node-neutral: #d2cac4;
+
/* Refactoring type accents — a qualitative palette (NOT semantic). Five
well-separated hues so the types stay distinguishable as dots / rails /
chips across the Refactoring surface. Don't fold these back into the
@@ -426,6 +450,15 @@
--color-info: #7da7d9; /* muted blue — distinct from the plum accent-secondary */
--color-caution: #d9b04a;
+ /* Canvas node ramp (dark) — see the light block for why this is not the ink.
+ Deeper and less saturated than the semantic vars so a field of thousands
+ reads as pigment rather than as light. */
+ --color-node-critical: #b0544b;
+ --color-node-poor: #bd7c42;
+ --color-node-fair: #a89453;
+ --color-node-good: #42906f;
+ --color-node-neutral: #333336;
+
/* Refactoring type accents — qualitative palette (dark theme, brighter). */
--color-refactor-extract-class: #f59520; /* amber */
--color-refactor-extract-helper: #34d399; /* green */
diff --git a/packages/vscode/webview/src/views/health/App.test.tsx b/packages/vscode/webview/src/views/health/App.test.tsx
index e207091bb..1ce4178c5 100644
--- a/packages/vscode/webview/src/views/health/App.test.tsx
+++ b/packages/vscode/webview/src/views/health/App.test.tsx
@@ -7,6 +7,7 @@ import type {
HealthTrendResponse,
} from "@repowise-dev/types/health";
import { OVERLAY_SPECS } from "@repowise-dev/ui/health/code-health-map";
+import { scoreBand, scoreTextColor } from "@repowise-dev/ui/health/tokens";
import type { WebviewHost } from "../../runtime/rpc";
import { App } from "./App";
@@ -174,7 +175,7 @@ describe("Health dashboard", () => {
expect(screen.getByText("demo-repo")).toBeTruthy();
});
- it("paints a focused file's score the colour the map paints the same file", async () => {
+ it("bands a focused file's score the way the map bands the same file", async () => {
const { host } = makeHost();
render(
<App
@@ -186,16 +187,21 @@ describe("Health dashboard", () => {
);
const figure = await screen.findByText("7.6");
- const mapFill = OVERLAY_SPECS.health.fill(
- files.files.find((f) => f.file_path === "src/mid.py")!,
- );
+ const file = files.files.find((f) => f.file_path === "src/mid.py")!;
// The contradiction this replaced: the panel called 7.6 green while the
- // canvas beside it coloured the same node amber. A passing render test
- // would not have caught that, so assert against the map's own fill table
- // rather than against a colour written out here a third time.
- expect(mapFill).toBe("var(--color-caution)");
- expect(figure.className).toContain(mapFill);
+ // canvas beside it coloured the same node amber.
+ //
+ // The two are no longer the same colour value, and must not be asserted to
+ // be. Inking text and filling a disc are different jobs, so the map paints
+ // from the canvas ramp and the panel from the semantic one. What may never
+ // differ is the band beneath both, which is what this pins: the map fills
+ // the node token for this file's band, and the figure carries the ink that
+ // the same band function gives the same score.
+ const band = scoreBand(file.score);
+ expect(band).toBe("fair");
+ expect(OVERLAY_SPECS.health.fill(file)).toBe(`var(--color-node-${band})`);
+ expect(figure.className).toContain(scoreTextColor(file.score));
});
it("shows an error panel when the host fails", async () => {