Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

fix(ui): chart-standard compliance sweep — honest axes, real knee, bound bins

Martin Vogelb7f227617a97
diff --git a/graph-ui/src/components/ControlTab.tsx b/graph-ui/src/components/ControlTab.tsx
index 32156f736..f0523b21b 100644
--- a/graph-ui/src/components/ControlTab.tsx
+++ b/graph-ui/src/components/ControlTab.tsx
@@ -9,18 +9,34 @@ function Gauge({ label, value, max, unit, color }: {
label: string; value: number; max: number; unit: string; color: string;
}) {
const pct = Math.min(100, (value / max) * 100);
+ /* The bands are stated in the legend and glyphed beside the value, so the
+ * bar's color is redundant, not the only carrier (WCAG 1.4.1). */
+ const band = pct > 80 ? "crit" : pct > 50 ? "warn" : null;
+ const bandColor = band === "crit" ? "#e05252" : "#eab308";
return (
<div className="flex-1 rounded-md border border-border/30 bg-card p-4">
<p className="text-[12px] text-foreground/40 uppercase tracking-widest mb-2">{label}</p>
<p className={`text-[20px] font-semibold tabular-nums ${color}`}>
{value.toFixed(1)}<span className="text-[13px] text-foreground/45 ml-1">{unit}</span>
+ {band && (
+ <span
+ className="text-[12px] ml-1.5 align-middle"
+ style={{ color: bandColor }}
+ title={`above ${(max * (band === "crit" ? 0.8 : 0.5)).toFixed(0)}${unit}`}
+ >
+ {band === "crit" ? "▲▲" : "▲"}
+ </span>
+ )}
</p>
<div className="mt-2 h-1.5 rounded-full bg-surface-3 overflow-hidden">
<div
className="h-full rounded-full transition-all duration-500"
- style={{ width: `${pct}%`, backgroundColor: pct > 80 ? "#e05252" : pct > 50 ? "#eab308" : "#1DA27E" }}
+ style={{ width: `${pct}%`, backgroundColor: band === "crit" ? "#e05252" : band === "warn" ? "#eab308" : "#1DA27E" }}
/>
</div>
+ <p className="mt-1.5 text-[12px] text-foreground/30 tabular-nums">
+ ▲ &gt;{(max * 0.5).toFixed(0)}{unit} · ▲▲ &gt;{(max * 0.8).toFixed(0)}{unit}
+ </p>
</div>
);
}
diff --git a/graph-ui/src/components/DashboardTab.tsx b/graph-ui/src/components/DashboardTab.tsx
index fe729c7ec..1991d1fc9 100644
--- a/graph-ui/src/components/DashboardTab.tsx
+++ b/graph-ui/src/components/DashboardTab.tsx
@@ -7,6 +7,12 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { kneeCount, costSentence, findingKey, isDismissed, dismiss } from "../lib/findings";
+import {
+ CPLX_BINS,
+ CPLX_TAIL_MIN,
+ CPLX_TAIL_START,
+ complexityTakeaway,
+} from "../lib/complexity";
import { MetricChip } from "./MetricChip";
interface MetricEntry {
@@ -58,27 +64,63 @@ interface DashboardTabProps {
onOpenWiki: (slug: string) => void;
}
-const CPLX_LABELS = ["1", "2–5", "6–10", "11–20", "21–50", ">50"];
+interface TrendPoint {
+ /* Epoch ms of the snapshot; NaN when the timestamp failed to parse. */
+ t: number;
+ v: number;
+}
-function Sparkline({ points }: { points: number[] }) {
+/* Shape-only sparkline on a real time axis — reindex snapshots are
+ * irregular, so equal spacing would lie about the pace of change. Each
+ * snapshot is a dot; lines only join runs of ≥4 snapshots, and never span
+ * a gap wider than 3× the median gap (a segment across a dark period
+ * invents data). The printed delta beside it carries the magnitude. */
+function Sparkline({ points }: { points: TrendPoint[] }) {
if (points.length < 2) return null;
- const max = Math.max(...points);
- const min = Math.min(...points);
+ const values = points.map((point) => point.v);
+ const max = Math.max(...values);
+ const min = Math.min(...values);
const span = max - min || 1;
- const coords = points
- .map(
- (point, index) =>
- `${(index / (points.length - 1)) * 100},${28 - ((point - min) / span) * 24}`,
- )
- .join(" ");
+ const t0 = points[0].t;
+ const tN = points[points.length - 1].t;
+ const timed = points.every((point) => Number.isFinite(point.t)) && tN > t0;
+ const xs = points.map((point, index) =>
+ timed ? ((point.t - t0) / (tN - t0)) * 100 : (index / (points.length - 1)) * 100,
+ );
+ const ys = values.map((value) => 28 - ((value - min) / span) * 24);
+ const gaps = xs.slice(1).map((x, index) => x - xs[index]);
+ const medianGap = [...gaps].sort((a, b) => a - b)[Math.floor(gaps.length / 2)] || 1;
+ const runs: string[][] = [[`${xs[0]},${ys[0]}`]];
+ for (let i = 1; i < xs.length; i++) {
+ if (gaps[i - 1] > 3 * medianGap) runs.push([]);
+ runs[runs.length - 1].push(`${xs[i]},${ys[i]}`);
+ }
return (
<svg viewBox="0 0 100 30" className="w-full h-[28px] mt-1" preserveAspectRatio="none">
- <polyline
- points={coords}
+ {points.length >= 4 &&
+ runs
+ .filter((run) => run.length > 1)
+ .map((run, index) => (
+ <polyline
+ key={index}
+ points={run.join(" ")}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ className="text-primary/50"
+ vectorEffect="non-scaling-stroke"
+ />
+ ))}
+ {/* Dots as zero-length round-capped strokes — with preserveAspectRatio
+ * "none", circles would stretch into ellipses; non-scaling strokes
+ * don't. */}
+ <path
+ d={xs.map((x, index) => `M${x},${ys[index]}h0.01`).join("")}
fill="none"
stroke="currentColor"
- strokeWidth="1.5"
- className="text-primary/50"
+ strokeWidth="3"
+ strokeLinecap="round"
+ className="text-primary/60"
vectorEffect="non-scaling-stroke"
/>
</svg>
@@ -91,13 +133,19 @@ function QualityCard({
sub,
tone,
trend,
+ trendFormat,
}: {
label: ReactNode;
value: string;
sub?: string;
tone?: "warn" | "crit";
- trend?: number[];
+ trend?: TrendPoint[];
+ trendFormat?: (v: number) => string;
}) {
+ const fmt = trendFormat ?? ((v: number) => v.toLocaleString("en-US"));
+ const first = trend?.[0]?.v;
+ const last = trend?.[trend.length - 1]?.v;
+ const delta = first !== undefined && last !== undefined ? last - first : 0;
return (
<div className="bg-card border border-border/50 rounded-md p-4 min-w-0">
<p className="text-[12px] uppercase tracking-widest text-foreground/40">{label}</p>
@@ -109,7 +157,17 @@ function QualityCard({
{value}
</p>
{sub && <p className="text-[12px] text-foreground/40 mt-0.5">{sub}</p>}
- {trend && trend.length > 1 && <Sparkline points={trend} />}
+ {trend && trend.length > 1 && (
+ <>
+ <Sparkline points={trend} />
+ {/* The min–max band makes any wobble fill it — this pair is the
+ * honest magnitude. */}
+ <p className="text-[12px] tabular-nums text-foreground/40 mt-0.5">
+ {fmt(first!)} → {fmt(last!)} ({delta > 0 ? "+" : ""}
+ {fmt(delta)})
+ </p>
+ </>
+ )}
</div>
);
}
@@ -229,17 +287,10 @@ export function DashboardTab({
const takeaway = useMemo(() => {
if (!metrics) return null;
- const hist = metrics.complexity_hist;
- const total = hist.reduce((a, b) => a + b, 0);
- if (total === 0) return null;
- const simple = hist[0] + hist[1];
- const tail = hist[4] + hist[5];
- const names = metrics.top_complex
- .slice(0, 3)
- .map((entry) => entry.name)
- .filter(Boolean)
- .join(", ");
- return `${((simple / total) * 100).toFixed(0)}% of functions are simple (≤5); ${tail.toLocaleString("en-US")} exceed 20${names ? ` — led by ${names}` : ""}.`;
+ return complexityTakeaway(
+ metrics.complexity_hist,
+ metrics.top_complex.slice(0, 3).map((entry) => entry.name ?? ""),
+ );
}, [metrics]);
if (error) {
@@ -284,6 +335,8 @@ export function DashboardTab({
{metrics.top_churn_complex.length > 0 && (
<span className="text-[12px] uppercase tracking-widest text-foreground/35 tabular-nums">
top {metrics.top_churn_complex.length.toLocaleString("en-US")}
+ {metrics.churn_total_files > 0 &&
+ ` of ${metrics.churn_total_files.toLocaleString("en-US")}`}
</span>
)}
{hero.mutedCount > 0 && (
@@ -327,7 +380,15 @@ export function DashboardTab({
<span className="text-[12px] tabular-nums text-foreground/45 shrink-0">
{entry.commits?.toLocaleString("en-US") ?? "?"} commits
</span>
- <span className="text-[12px] tabular-nums text-foreground/35 shrink-0 w-20 text-right">
+ {/* The score is commits × max complexity — dividing the
+ * factor back out shows both axes, not just the ranking. */}
+ <span className="text-[12px] tabular-nums text-foreground/45 shrink-0 w-16 text-right">
+ cplx {entry.commits ? Math.round(entry.value / entry.commits).toLocaleString("en-US") : "?"}
+ </span>
+ <span
+ className="text-[12px] tabular-nums text-foreground/35 shrink-0 w-20 text-right"
+ title="churn × complexity score — orders the list"
+ >
{entry.value.toLocaleString("en-US")}
</span>
<button
@@ -357,7 +418,11 @@ export function DashboardTab({
value={`${(resolvedShare * 100).toFixed(0)}%`}
sub={`${certainty.usage.toLocaleString("en-US")} USAGE edges unproven`}
tone={resolvedShare < 0.6 ? "warn" : undefined}
- trend={history.map((entry) => 1 - entry.usage_share)}
+ trend={history.map((entry) => ({
+ t: Date.parse(entry.indexed_at),
+ v: 1 - entry.usage_share,
+ }))}
+ trendFormat={(v) => `${(v * 100).toFixed(0)}%`}
/>
<QualityCard
label={
@@ -368,7 +433,10 @@ export function DashboardTab({
value={totals.dead.toLocaleString("en-US")}
sub="no callers; entry/test/exported excluded"
tone={totals.dead > 0 ? "warn" : undefined}
- trend={history.map((entry) => entry.dead)}
+ trend={history.map((entry) => ({
+ t: Date.parse(entry.indexed_at),
+ v: entry.dead,
+ }))}
/>
<QualityCard
label={
@@ -378,7 +446,10 @@ export function DashboardTab({
}
value={`${(testedShare * 100).toFixed(0)}%`}
sub={`${totals.tested_symbols.toLocaleString("en-US")} with TESTS edges`}
- trend={history.map((entry) => entry.tested)}
+ trend={history.map((entry) => ({
+ t: Date.parse(entry.indexed_at),
+ v: entry.tested,
+ }))}
/>
<QualityCard
label={
@@ -395,24 +466,40 @@ export function DashboardTab({
{/* ── Complexity, with its takeaway ─────────────────────── */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3 mb-4">
<div className="bg-card border border-border/50 rounded-md p-4">
- <p className="text-[12px] uppercase tracking-widest text-foreground/40">
- Complexity distribution
+ <p className="text-[12px] uppercase tracking-widest text-foreground/40 flex items-baseline justify-between gap-2">
+ <span>Complexity mix</span>
+ <span className="text-foreground/30 tabular-nums shrink-0">
+ {totals.callables.toLocaleString("en-US")} callables
+ </span>
</p>
{takeaway && <p className="text-[13px] text-foreground/60 mt-1">{takeaway}</p>}
- <div className="flex items-end gap-1.5 h-[64px] mt-3">
+ {/* TODO(W2b): real log-binned histogram behind a disclosure — needs per-bin API data */}
+ <div className="flex items-end gap-1.5 h-[84px] mt-3">
{metrics.complexity_hist.map((value, index) => {
const max = Math.max(1, ...metrics.complexity_hist);
return (
- <div key={index} className="flex-1 flex flex-col items-center gap-1 min-w-0">
+ <div
+ key={index}
+ className="flex-1 flex flex-col items-center justify-end gap-1 min-w-0"
+ >
+ <span className="text-[12px] tabular-nums text-foreground/45">
+ {value.toLocaleString("en-US")}
+ </span>
<div
- className={`w-full rounded-sm ${index >= 4 ? "bg-warn/60" : "bg-primary/35"}`}
+ className={`w-full rounded-sm ${index >= CPLX_TAIL_START ? "bg-warn/60" : "bg-primary/35"}`}
style={{ height: `${Math.max(2, (value / max) * 40)}px` }}
/>
- <span className="text-[12px] text-foreground/35">{CPLX_LABELS[index]}</span>
+ <span className="text-[12px] text-foreground/35">
+ {CPLX_BINS[index]?.label}
+ </span>
</div>
);
})}
</div>
+ <p className="text-[12px] text-foreground/35 mt-1.5">
+ <span className="inline-block w-2 h-2 rounded-sm bg-warn/60 mr-1" />
+ &gt;{CPLX_TAIL_MIN} flagged
+ </p>
</div>
<TopList
title="Most churned files (1y)"
diff --git a/graph-ui/src/components/ModulesTab.tsx b/graph-ui/src/components/ModulesTab.tsx
index fd7d358ed..c75d48931 100644
--- a/graph-ui/src/components/ModulesTab.tsx
+++ b/graph-ui/src/components/ModulesTab.tsx
@@ -203,6 +203,11 @@ export function ModulesTab({
</div>
) : viewMode === "bars" ? (
<div className="h-full overflow-y-auto pr-2">
+ {/* Bars are scaled to the largest sibling, not the whole —
+ * without saying so, they read as share-of-total. */}
+ <p className="text-[12px] text-foreground/35 px-2 pb-1">
+ bar length: relative to largest module
+ </p>
{[...tree.children]
.sort((a, b) => b.symbols - a.symbols)
.map((child) => {
diff --git a/graph-ui/src/components/OverviewTab.tsx b/graph-ui/src/components/OverviewTab.tsx
index fa9679e94..3e73f4299 100644
--- a/graph-ui/src/components/OverviewTab.tsx
+++ b/graph-ui/src/components/OverviewTab.tsx
@@ -106,6 +106,51 @@ function Slot({
);
}
+/* All displayed regions' cohesion values as an inline dot strip — a bare
+ * value invites misreading (0.4 can be the tightest region on the map or
+ * the loosest). This region's dot is emphasized; the tick is the median. */
+function CohesionStrip({ values, own }: { values: number[]; own: number }) {
+ if (values.length < 2) return null;
+ const sorted = [...values].sort((a, b) => a - b);
+ const mid = Math.floor(sorted.length / 2);
+ const median =
+ sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
+ const x = (value: number) => 4 + Math.max(0, Math.min(1, value)) * 112;
+ return (
+ <svg
+ width="120"
+ height="14"
+ viewBox="0 0 120 14"
+ className="shrink-0"
+ role="img"
+ aria-label={`cohesion ${own.toFixed(2)} among ${values.length} regions, median ${median.toFixed(2)}`}
+ >
+ <title>{`p50 = ${median.toFixed(2)}`}</title>
+ <line
+ x1={x(median)}
+ y1="2"
+ x2={x(median)}
+ y2="12"
+ stroke="currentColor"
+ strokeOpacity="0.35"
+ className="text-foreground"
+ />
+ {values.map((value, index) => (
+ <circle
+ key={index}
+ cx={x(value)}
+ cy="7"
+ r="1.5"
+ fill="currentColor"
+ fillOpacity="0.25"
+ className="text-foreground"
+ />
+ ))}
+ <circle cx={x(own)} cy="7" r="2.5" fill="currentColor" className="text-primary" />
+ </svg>
+ );
+}
+
export function OverviewTab({
project,
onOpenRegion,
@@ -423,10 +468,16 @@ export function OverviewTab({
{region.name}
</span>
</div>
- <p className="text-[12px] text-foreground/45 truncate tabular-nums">
- {region.members.toLocaleString("en-US")} symbols · cohesion{" "}
- {region.cohesion.toFixed(2)}
- </p>
+ <div className="flex items-center gap-2">
+ <p className="text-[12px] text-foreground/45 truncate tabular-nums flex-1 min-w-0">
+ {region.members.toLocaleString("en-US")} symbols · cohesion{" "}
+ {region.cohesion.toFixed(2)}
+ </p>
+ <CohesionStrip
+ values={displayRegions.map((r) => r.cohesion)}
+ own={region.cohesion}
+ />
+ </div>
{region.why && (
<p className="text-[12px] text-foreground/35 mt-1 line-clamp-2">
{region.why}
diff --git a/graph-ui/src/lib/complexity.test.ts b/graph-ui/src/lib/complexity.test.ts
new file mode 100644
index 000000000..6178697f8
--- /dev/null
+++ b/graph-ui/src/lib/complexity.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+import {
+ CPLX_BINS,
+ CPLX_SIMPLE_MAX,
+ CPLX_TAIL_MIN,
+ CPLX_TAIL_START,
+ complexityTakeaway,
+} from "./complexity";
+
+/* Parse a bin label back into its bounds so the text the user reads under
+ * the bars cannot drift from the numeric metadata the sentence derives
+ * from. "1" → [1,1], "2–5" → [2,5], ">50" → [51,∞]. */
+function parseLabel(label: string): { lo: number; hi: number } {
+ if (label.startsWith(">")) return { lo: Number(label.slice(1)) + 1, hi: Infinity };
+ const parts = label.split("–").map(Number);
+ const lo = parts[0];
+ const hi = parts.length > 1 ? parts[1] : parts[0];
+ expect(Number.isFinite(lo)).toBe(true);
+ expect(Number.isFinite(hi)).toBe(true);
+ return { lo, hi };
+}
+
+describe("complexity bins", () => {
+ it("labels agree with the numeric bounds and are contiguous", () => {
+ let expectedLo = 1;
+ for (const bin of CPLX_BINS) {
+ const parsed = parseLabel(bin.label);
+ expect(parsed.lo).toBe(expectedLo);
+ expect(parsed.hi).toBe(bin.hi);
+ expectedLo = bin.hi + 1;
+ }
+ });
+ it("derived thresholds match the labels the user sees", () => {
+ expect(CPLX_SIMPLE_MAX).toBe(parseLabel(CPLX_BINS[1].label).hi);
+ expect(CPLX_TAIL_MIN).toBe(parseLabel(CPLX_BINS[CPLX_TAIL_START].label).lo - 1);
+ });
+});
+
+describe("complexityTakeaway", () => {
+ it("claims exactly what the labels claim", () => {
+ const hist = [4, 6, 3, 2, 1, 1];
+ const sentence = complexityTakeaway(hist, [])!;
+ /* Recount from the label-parsed bounds, independent of the metadata. */
+ const simple = hist
+ .filter((_, index) => parseLabel(CPLX_BINS[index].label).hi <= CPLX_SIMPLE_MAX)
+ .reduce((a, b) => a + b, 0);
+ const tail = hist
+ .filter((_, index) => parseLabel(CPLX_BINS[index].label).lo > CPLX_TAIL_MIN)
+ .reduce((a, b) => a + b, 0);
+ const total = hist.reduce((a, b) => a + b, 0);
+ expect(sentence).toBe(
+ `${((simple / total) * 100).toFixed(0)}% of functions are simple (≤${CPLX_SIMPLE_MAX}); ${tail} exceed ${CPLX_TAIL_MIN}.`,
+ );
+ });
+ it("appends the leading names when given", () => {
+ expect(complexityTakeaway([10, 0, 0, 0, 0, 2], ["a", "b"])).toContain("— led by a, b");
+ });
+ it("returns null on an empty population", () => {
+ expect(complexityTakeaway([0, 0, 0, 0, 0, 0], [])).toBeNull();
+ });
+});
diff --git a/graph-ui/src/lib/complexity.ts b/graph-ui/src/lib/complexity.ts
new file mode 100644
index 000000000..0db9c8b47
--- /dev/null
+++ b/graph-ui/src/lib/complexity.ts
@@ -0,0 +1,38 @@
+/* Complexity bins — the single source of truth for the dashboard's
+ * histogram labels and the takeaway sentence. The sentence's bin claims
+ * ("simple (≤5)", "exceed 20") derive from this table, and a test binds
+ * label text to the numeric bounds, so a label edit cannot silently lie. */
+
+export interface CplxBin {
+ label: string;
+ /* Inclusive upper bound; Infinity for the open tail bin. */
+ hi: number;
+}
+
+export const CPLX_BINS: CplxBin[] = [
+ { label: "1", hi: 1 },
+ { label: "2–5", hi: 5 },
+ { label: "6–10", hi: 10 },
+ { label: "11–20", hi: 20 },
+ { label: "21–50", hi: 50 },
+ { label: ">50", hi: Infinity },
+];
+
+/* The takeaway's two claims: "simple" = the first two bins, the flagged
+ * tail = the last two. Both thresholds are read off the table. */
+export const CPLX_SIMPLE_MAX = CPLX_BINS[1].hi;
+export const CPLX_TAIL_START = CPLX_BINS.length - 2;
+export const CPLX_TAIL_MIN = CPLX_BINS[CPLX_TAIL_START - 1].hi;
+
+export function complexityTakeaway(hist: number[], names: string[]): string | null {
+ const total = hist.reduce((a, b) => a + b, 0);
+ if (total === 0) return null;
+ const simple = hist
+ .filter((_, index) => CPLX_BINS[index] && CPLX_BINS[index].hi <= CPLX_SIMPLE_MAX)
+ .reduce((a, b) => a + b, 0);
+ const tail = hist
+ .filter((_, index) => index >= CPLX_TAIL_START)
+ .reduce((a, b) => a + b, 0);
+ const led = names.filter(Boolean).join(", ");
+ return `${((simple / total) * 100).toFixed(0)}% of functions are simple (≤${CPLX_SIMPLE_MAX}); ${tail.toLocaleString("en-US")} exceed ${CPLX_TAIL_MIN}${led ? ` — led by ${led}` : ""}.`;
+}
diff --git a/graph-ui/src/lib/findings.test.ts b/graph-ui/src/lib/findings.test.ts
index cdcbdc357..9f86910a5 100644
--- a/graph-ui/src/lib/findings.test.ts
+++ b/graph-ui/src/lib/findings.test.ts
@@ -4,14 +4,34 @@ import { isTestRegion, lensRegionsPayload, isBuiltinQn } from "./regions";
import type { RegionsPayload } from "./types";
describe("kneeCount", () => {
- it("finds the largest relative drop", () => {
+ it("separates a clear head from a flat tail", () => {
/* 100, 90, 85 | 20, 18 — the knee is after the third item. */
expect(kneeCount([100, 90, 85, 20, 18])).toBe(3);
});
+ it("does not collapse to rank 1 on power-law data", () => {
+ /* ~1000/rank — the old largest-relative-drop rule returned 1 here. */
+ const powerLaw = [1000, 500, 333, 250, 200, 167, 143, 125, 111, 100];
+ expect(kneeCount(powerLaw)).toBeGreaterThanOrEqual(3);
+ expect(kneeCount(powerLaw)).toBeLessThanOrEqual(5);
+ });
+ it("finds an obvious elbow", () => {
+ /* Four high values, then a cliff — the head is those four. */
+ expect(kneeCount([100, 98, 96, 94, 15, 14, 13, 12])).toBe(4);
+ });
+ it("returns the clamp floor on a monotone gentle series", () => {
+ expect(kneeCount([100, 97, 94, 91, 88, 85, 82, 79, 76, 73])).toBe(3);
+ });
+ it("never exceeds half the list nor 15", () => {
+ const flat = Array.from({ length: 100 }, (_, i) => 1000 - i);
+ expect(kneeCount(flat)).toBeLessThanOrEqual(15);
+ expect(kneeCount([9, 8, 7, 2, 1, 1])).toBeLessThanOrEqual(3);
+ });
it("degenerates safely", () => {
expect(kneeCount([])).toBe(0);
expect(kneeCount([5])).toBe(1);
- expect(kneeCount([5, 5, 5])).toBe(1);
+ expect(kneeCount([5, 5])).toBe(2);
+ expect(kneeCount([5, 5, 5])).toBe(3);
+ expect(kneeCount([0, 0, 0, 0, 0])).toBe(3);
});
});
diff --git a/graph-ui/src/lib/findings.ts b/graph-ui/src/lib/findings.ts
index 98bc2edfd..669ed5ef0 100644
--- a/graph-ui/src/lib/findings.ts
+++ b/graph-ui/src/lib/findings.ts
@@ -1,24 +1,40 @@
/* Findings machinery: knee-point cutoffs, the cost sentence, and finding
* dismissals — the difference between a dashboard and a number museum. */
-/* Knee of a descending score list: the index AFTER which the largest
- * relative drop occurs — "the head that matters" (CodeScene's refusal to
- * show 5,000 items). Returns at least 1, at most values.length. */
+/* Knee of a descending score list — how many head items deserve emphasis:
+ * "the head that matters" (CodeScene's refusal to show 5,000 items).
+ * Kneedle-style: normalize ranks and values to the unit square, smooth y
+ * with a centered 3-point moving average, and put the knee at the maximum
+ * of the difference curve against the descending chord y = 1 − x (the
+ * decreasing-data form of Kneedle's transform). A largest-relative-drop
+ * rule sat here before and collapsed to the rank 1→2 gap on power-law
+ * data — the head became "top 1". Guard rails: the head stays within
+ * [3, 15], never exceeds half the list, and n < 5 falls back to min(3, n). */
export function kneeCount(values: number[]): number {
- if (values.length <= 1) return values.length;
- let bestIndex = 0;
- let bestRatio = 0;
- for (let i = 0; i < values.length - 1; i++) {
- const current = values[i];
- const next = values[i + 1];
- if (current <= 0) break;
- const ratio = (current - next) / current;
- if (ratio > bestRatio) {
- bestRatio = ratio;
- bestIndex = i;
+ const n = values.length;
+ if (n < 5) return Math.min(3, n);
+ const max = Math.max(...values);
+ if (max <= 0) return Math.min(3, n);
+ const y = values.map((value) => value / max);
+ const smoothed = y.map((_, i) => {
+ const lo = Math.max(0, i - 1);
+ const hi = Math.min(n - 1, i + 1);
+ let sum = 0;
+ for (let j = lo; j <= hi; j++) sum += y[j];
+ return sum / (hi - lo + 1);
+ });
+ /* The maximum sits where the curve has fallen furthest below the chord —
+ * the first rank of the flat tail, i.e. the size of the head. */
+ let knee = 0;
+ let best = -Infinity;
+ for (let i = 0; i < n; i++) {
+ const difference = 1 - i / (n - 1) - smoothed[i];
+ if (difference > best) {
+ best = difference;
+ knee = i;
}
}
- return bestIndex + 1;
+ return Math.min(Math.max(knee, 3), Math.min(15, Math.ceil(n / 2)));
}
/* "9 files — 1.1% of the codebase, 34% of all commits this year." */
diff --git a/graph-ui/tsconfig.tsbuildinfo b/graph-ui/tsconfig.tsbuildinfo
index d93723852..26070f32e 100644
--- a/graph-ui/tsconfig.tsbuildinfo
+++ b/graph-ui/tsconfig.tsbuildinfo
@@ -1 +1 @@
-{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/rpc.ts","./src/components/changestab.tsx","./src/components/commandk.tsx","./src/components/controltab.tsx","./src/components/dashboardtab.tsx","./src/components/displaysettingsmenu.tsx","./src/components/edgelines.tsx","./src/components/errorboundary.tsx","./src/components/filterpanel.tsx","./src/components/flowstab.tsx","./src/components/graphloader.tsx","./src/components/graphscene.test.ts","./src/components/graphscene.tsx","./src/components/graphtab.deadcode.test.tsx","./src/components/graphtab.filters.test.tsx","./src/components/graphtab.regions.test.tsx","./src/components/graphtab.test.ts","./src/components/graphtab.tsx","./src/components/halolayer.tsx","./src/components/metricchip.tsx","./src/components/minimap.tsx","./src/components/missedcallout.tsx","./src/components/modulestab.tsx","./src/components/nodecloud.tsx","./src/components/nodedetailpanel.showmore.test.tsx","./src/components/nodedetailpanel.test.tsx","./src/components/nodedetailpanel.tsx","./src/components/nodelabels.tsx","./src/components/nodetooltip.tsx","./src/components/overviewtab.tsx","./src/components/projectcard.tsx","./src/components/projectswitcher.tsx","./src/components/promptbasket.tsx","./src/components/regionpanel.tsx","./src/components/regiontooltip.tsx","./src/components/resizehandle.tsx","./src/components/sidebar.tsx","./src/components/statstab.test.tsx","./src/components/statstab.tsx","./src/components/symboltab.tsx","./src/components/tabbar.tsx","./src/components/triggertree.tsx","./src/components/wikipanel.test.tsx","./src/components/wikipanel.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/card.tsx","./src/components/ui/checkbox.tsx","./src/components/ui/input.tsx","./src/components/ui/scroll-area.tsx","./src/components/ui/separator.tsx","./src/hooks/usegraphdata.test.ts","./src/hooks/usegraphdata.ts","./src/hooks/useprojects.ts","./src/lib/atlas.test.ts","./src/lib/atlas.ts","./src/lib/colors.ts","./src/lib/composer.ts","./src/lib/density.test.ts","./src/lib/density.ts","./src/lib/findings.test.ts","./src/lib/findings.ts","./src/lib/firstread.ts","./src/lib/flowgroup.test.ts","./src/lib/flowgroup.ts","./src/lib/i18n.test.ts","./src/lib/i18n.ts","./src/lib/regions.test.ts","./src/lib/regions.ts","./src/lib/treemap.ts","./src/lib/types.ts","./src/lib/utils.ts","./src/lib/why.test.ts","./src/lib/why.ts","./src/lib/whyfetch.ts","./src/wiki/entries.test.ts","./src/wiki/entries.ts"],"version":"5.9.3"}
\ No newline at end of file
+{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/rpc.ts","./src/components/changestab.tsx","./src/components/commandk.tsx","./src/components/controltab.tsx","./src/components/dashboardtab.tsx","./src/components/displaysettingsmenu.tsx","./src/components/edgelines.tsx","./src/components/errorboundary.tsx","./src/components/filterpanel.tsx","./src/components/flowstab.tsx","./src/components/graphloader.tsx","./src/components/graphscene.test.ts","./src/components/graphscene.tsx","./src/components/graphtab.deadcode.test.tsx","./src/components/graphtab.filters.test.tsx","./src/components/graphtab.regions.test.tsx","./src/components/graphtab.test.ts","./src/components/graphtab.tsx","./src/components/halolayer.tsx","./src/components/metricchip.tsx","./src/components/minimap.tsx","./src/components/missedcallout.tsx","./src/components/modulestab.tsx","./src/components/nodecloud.tsx","./src/components/nodedetailpanel.showmore.test.tsx","./src/components/nodedetailpanel.test.tsx","./src/components/nodedetailpanel.tsx","./src/components/nodelabels.tsx","./src/components/nodetooltip.tsx","./src/components/overviewtab.tsx","./src/components/projectcard.tsx","./src/components/projectswitcher.tsx","./src/components/promptbasket.tsx","./src/components/regionpanel.tsx","./src/components/regiontooltip.tsx","./src/components/resizehandle.tsx","./src/components/sidebar.tsx","./src/components/statstab.test.tsx","./src/components/statstab.tsx","./src/components/symboltab.tsx","./src/components/tabbar.tsx","./src/components/triggertree.tsx","./src/components/wikipanel.test.tsx","./src/components/wikipanel.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/card.tsx","./src/components/ui/checkbox.tsx","./src/components/ui/input.tsx","./src/components/ui/scroll-area.tsx","./src/components/ui/separator.tsx","./src/hooks/usegraphdata.test.ts","./src/hooks/usegraphdata.ts","./src/hooks/useprojects.ts","./src/lib/atlas.test.ts","./src/lib/atlas.ts","./src/lib/colors.ts","./src/lib/complexity.test.ts","./src/lib/complexity.ts","./src/lib/composer.ts","./src/lib/density.test.ts","./src/lib/density.ts","./src/lib/findings.test.ts","./src/lib/findings.ts","./src/lib/firstread.ts","./src/lib/flowgroup.test.ts","./src/lib/flowgroup.ts","./src/lib/i18n.test.ts","./src/lib/i18n.ts","./src/lib/regions.test.ts","./src/lib/regions.ts","./src/lib/treemap.ts","./src/lib/types.ts","./src/lib/utils.ts","./src/lib/why.test.ts","./src/lib/why.ts","./src/lib/whyfetch.ts","./src/wiki/entries.test.ts","./src/wiki/entries.ts"],"version":"5.9.3"}
\ No newline at end of file