Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(ui): decisions guards + enforcement prompt, honest stats labels, health-drawer polish (#715)
Swati Ahujabd141af8fdd3
diff --git a/packages/ui/__tests__/decisions/decision-detail.test.tsx b/packages/ui/__tests__/decisions/decision-detail.test.tsxindex 86308b866..f98219d74 100644--- a/packages/ui/__tests__/decisions/decision-detail.test.tsx+++ b/packages/ui/__tests__/decisions/decision-detail.test.tsx@@ -119,6 +119,35 @@ describe("DecisionDetail", () => {expect(await screen.findByText("Evolution")).toBeInTheDocument();});+ it("renders a dash instead of 'Invalid Date' when created_at is missing", () => {+ renderView(+ <DecisionDetail+ decision={makeDecision({ created_at: undefined as unknown as string })}+ adapter={makeAdapter()}+ />,+ );+ expect(screen.getByText("Created: —")).toBeInTheDocument();+ expect(screen.queryByText(/Invalid Date/i)).not.toBeInTheDocument();+ });++ it("explains what Confirm/Dismiss do next to the buttons", () => {+ renderView(<DecisionDetail decision={makeDecision()} adapter={makeAdapter()} />);+ expect(+ screen.getByText(/Confirm marks this as an accurate, current decision/),+ ).toBeInTheDocument();+ });++ it("offers the enforcement prompt only for active decisions", () => {+ const { unmount } = renderView(+ <DecisionDetail decision={makeDecision({ status: "active" })} adapter={makeAdapter()} />,+ );+ expect(screen.getByRole("button", { name: /Enforce this decision/ })).toBeInTheDocument();+ unmount();++ renderView(<DecisionDetail decision={makeDecision()} adapter={makeAdapter()} />);+ expect(screen.queryByRole("button", { name: /Enforce this decision/ })).not.toBeInTheDocument();+ });+it("renders a host-supplied linked-issues slot, and nothing when omitted", () => {const withSlot = makeAdapter({renderLinkedIssues: () => <div>JIRA-123 linked</div>,diff --git a/packages/ui/__tests__/health/health-file-drawer.test.tsx b/packages/ui/__tests__/health/health-file-drawer.test.tsxindex 8bd754f88..62bd868df 100644--- a/packages/ui/__tests__/health/health-file-drawer.test.tsx+++ b/packages/ui/__tests__/health/health-file-drawer.test.tsx@@ -70,3 +70,28 @@ describe("HealthFileDrawer finding grouping", () => {expect(screen.getByRole("button", { name: /_run_repo_checks/ })).toBeInTheDocument();});});++describe("HealthFileDrawer metric cards", () => {+ it("says 'not measured' instead of 0 when structural counters are absent", () => {+ render(+ <HealthFileDrawer+ open+ onClose={() => {}}+ metric={metric({ max_ccn: null, max_nesting: null, nloc: null })}+ />,+ );+ expect(screen.getAllByText("not measured")).toHaveLength(3);+ });++ it("still renders real zero values as numbers", () => {+ render(+ <HealthFileDrawer+ open+ onClose={() => {}}+ metric={metric({ max_ccn: 0, max_nesting: 0, nloc: 12 })}+ />,+ );+ expect(screen.queryByText("not measured")).not.toBeInTheDocument();+ expect(screen.getByText("12")).toBeInTheDocument();+ });+});diff --git a/packages/ui/src/decisions/decision-detail.tsx b/packages/ui/src/decisions/decision-detail.tsxindex 62adf50d3..3351bf173 100644--- a/packages/ui/src/decisions/decision-detail.tsx+++ b/packages/ui/src/decisions/decision-detail.tsx@@ -33,7 +33,10 @@ import { ConfirmDialog } from "../ui/confirm-dialog";import { stripMarkdown } from "../lib/format";import { AiPromptButton } from "../health/ai-prompt-button";import { AiPromptModal } from "../health/ai-prompt-modal";-import { buildDecisionAiPrompt } from "../health/ai-prompt-builder";+import {+ buildDecisionAiPrompt,+ buildDecisionEnforcementAiPrompt,+} from "../health/ai-prompt-builder";import { ModuleLinkEditor } from "./module-link-editor";import { VerificationBadge } from "./verification-badge";@@ -89,7 +92,9 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {const [linkedFiles, setLinkedFiles] = React.useState(decision.affected_files);const [linkageSaving, setLinkageSaving] = React.useState(false);const [evidenceOpen, setEvidenceOpen] = React.useState(false);- const [promptOpen, setPromptOpen] = React.useState(false);+ // Which AI-prompt flavor the modal shows: verification ("is this decision+ // still true?") or enforcement ("make the code conform to it").+ const [promptMode, setPromptMode] = React.useState<"verify" | "enforce" | null>(null);// Lineage: cheap, load eagerly so the Evolution timeline renders when present.const { data: lineage } = useSWR(@@ -258,9 +263,15 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {)}<AiPromptButtonlabel={status === "proposed" ? "Verify & confirm with AI" : "Verify with AI"}- onClick={() => setPromptOpen(true)}+ onClick={() => setPromptMode("verify")}className="ml-auto"/>+ {status === "active" && (+ <AiPromptButton+ label="Enforce this decision"+ onClick={() => setPromptMode("enforce")}+ />+ )}<buttontype="button"onClick={() => setEvidenceOpen(true)}@@ -278,7 +289,7 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {Staleness: {decision.staleness_score.toFixed(2)}</span>)}- <span>Created: {new Date(decision.created_at).toLocaleDateString()}</span>+ <span>Created: {formatDateOrDash(decision.created_at)}</span></div></div>@@ -331,8 +342,7 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {<div className="space-y-2 text-sm">{decision.last_code_change && (<p className="text-xs text-[var(--color-text-tertiary)]">- Affected files last changed{" "}- {new Date(decision.last_code_change).toLocaleDateString()}.+ Affected files last changed {formatDateOrDash(decision.last_code_change)}.</p>)}<div className="flex flex-col gap-1.5">@@ -389,33 +399,49 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {)}{/* Actions */}- <div className="flex gap-2 border-t border-[var(--color-border-default)] pt-4">- {status === "proposed" && (- <>- <button- onClick={() => handleStatusChange("active")}- disabled={loading}- className="rounded-md bg-[var(--color-success)] px-3 py-1.5 text-sm font-medium text-[var(--color-text-inverse)] hover:opacity-90 disabled:opacity-50"- >- Confirm- </button>+ <div className="space-y-2 border-t border-[var(--color-border-default)] pt-4">+ <div className="flex gap-2">+ {status === "proposed" && (+ <>+ <button+ onClick={() => handleStatusChange("active")}+ disabled={loading}+ className="rounded-md bg-[var(--color-success)] px-3 py-1.5 text-sm font-medium text-[var(--color-text-inverse)] hover:opacity-90 disabled:opacity-50"+ >+ Confirm+ </button>+ <button+ onClick={() => handleStatusChange("deprecated")}+ disabled={loading}+ className="rounded-md border border-[var(--color-border-default)] px-3 py-1.5 text-sm text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] disabled:opacity-50"+ >+ Dismiss+ </button>+ </>+ )}+ {status === "active" && (<buttononClick={() => handleStatusChange("deprecated")}disabled={loading}- className="rounded-md border border-[var(--color-border-default)] px-3 py-1.5 text-sm text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] disabled:opacity-50"+ className="rounded-md border border-[var(--color-error)]/40 px-3 py-1.5 text-sm text-[var(--color-error)] hover:bg-[var(--color-error)]/10 disabled:opacity-50">- Dismiss+ Deprecate</button>- </>+ )}+ </div>+ {status === "proposed" && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Confirm marks this as an accurate, current decision for your team.+ Dismiss hides it from the active list as inaccurate or no longer+ relevant. Neither changes any code.+ </p>)}{status === "active" && (- <button- onClick={() => handleStatusChange("deprecated")}- disabled={loading}- className="rounded-md border border-[var(--color-error)]/40 px-3 py-1.5 text-sm text-[var(--color-error)] hover:bg-[var(--color-error)]/10 disabled:opacity-50"- >- Deprecate- </button>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Deprecate marks this decision as no longer current — existing+ references remain, but it stops being treated as the standard. It+ doesn't change any code.+ </p>)}</div>{confirmConfig && (@@ -441,10 +467,12 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {/><AiPromptModal- open={promptOpen}- onOpenChange={setPromptOpen}+ open={promptMode !== null}+ onOpenChange={(o) => !o && setPromptMode(null)}getPrompt={(flavor) =>- buildDecisionAiPrompt({+ (promptMode === "enforce"+ ? buildDecisionEnforcementAiPrompt+ : buildDecisionAiPrompt)({decision: {title: decision.title,status,@@ -462,13 +490,29 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {})}filePath={stripMarkdown(decision.title)}- title="AI decision verification"- description="A ready-to-paste prompt that has your AI agent check this decision against the current code and recommend whether to keep, update, or retire it."+ title={+ promptMode === "enforce"+ ? "AI decision enforcement"+ : "AI decision verification"+ }+ description={+ promptMode === "enforce"+ ? "A ready-to-paste prompt that has your AI agent audit the governed code for compliance with this decision and fix every violation it finds."+ : "A ready-to-paste prompt that has your AI agent check this decision against the current code and recommend whether to keep, update, or retire it."+ }/></div>);}+/** Older/hosted backends can omit decision timestamps — render "—" instead of+ * "Invalid Date" for a missing or unparseable value. */+function formatDateOrDash(iso: string | null | undefined): string {+ if (!iso) return "—";+ const d = new Date(iso);+ return Number.isNaN(d.getTime()) ? "—" : d.toLocaleDateString();+}+function PrevNextLink({Link,href,diff --git a/packages/ui/src/decisions/decision-graph-view.tsx b/packages/ui/src/decisions/decision-graph-view.tsxindex 30e2bbb3c..823a8a02f 100644--- a/packages/ui/src/decisions/decision-graph-view.tsx+++ b/packages/ui/src/decisions/decision-graph-view.tsx@@ -39,6 +39,13 @@ import type {const DECISION_NODE_SIZE = { width: 200, height: 72 };const CODE_NODE_SIZE = { width: 180, height: 44 };+// ELK's layered layout runs on the main thread; an unbounded node set (one+// demo decision alone fans out into 160 code nodes) hangs the tab. Cap the+// per-decision code fan-out and the total node count, and say what was+// dropped instead of freezing.+const MAX_CODE_LINKS_PER_DECISION = 8;+const MAX_LAYOUT_NODES = 300;+const STATUS_DOT: Record<string, string> = {active: "var(--color-success)",proposed: "var(--color-info)",@@ -222,10 +229,17 @@ interface LayoutResult {nodes: Node[];edges: Edge[];loading: boolean;+ /** Human-readable note when the graph was capped for rendering. */+ truncationNote: string | null;}function useDecisionGraphLayout(graph: DecisionGraph | undefined, showCode: boolean): LayoutResult {- const [result, setResult] = useState<LayoutResult>({ nodes: [], edges: [], loading: false });+ const [result, setResult] = useState<LayoutResult>({+ nodes: [],+ edges: [],+ loading: false,+ truncationNote: null,+ });// Stable identity key so the effect only re-runs when content changes.const graphKey = useMemo(() => {@@ -240,23 +254,62 @@ function useDecisionGraphLayout(graph: DecisionGraph | undefined, showCode: booluseEffect(() => {if (!graph || graph.nodes.length === 0) {- setResult({ nodes: [], edges: [], loading: false });+ setResult({ nodes: [], edges: [], loading: false, truncationNote: null });return;}let cancelled = false;setResult((r) => ({ ...r, loading: true }));- const decisionIds = new Set(graph.nodes.map((n) => n.id));+ // ---- Bound the graph before ELK ever sees it ----+ // Decisions first: if they alone exceed the ceiling, keep the highest-+ // impact ones (impact = how much code a decision governs).+ const codeLinkCounts = new Map<string, number>();+ for (const e of graph.code_edges) {+ codeLinkCounts.set(e.decision_id, (codeLinkCounts.get(e.decision_id) ?? 0) + 1);+ }+ let decisionNodes = graph.nodes;+ let droppedDecisions = 0;+ if (decisionNodes.length > MAX_LAYOUT_NODES) {+ decisionNodes = [...decisionNodes]+ .sort((a, b) => (codeLinkCounts.get(b.id) ?? 0) - (codeLinkCounts.get(a.id) ?? 0))+ .slice(0, MAX_LAYOUT_NODES);+ droppedDecisions = graph.nodes.length - decisionNodes.length;+ }+ const decisionIds = new Set(decisionNodes.map((n) => n.id));- // Unique code node ids referenced by code edges.- const codeEdges = showCode ? graph.code_edges : [];+ // Code links: cap the fan-out per decision, then stop adding new code+ // nodes once the total node budget is spent.+ const allCodeEdges = showCode ? graph.code_edges : [];+ const perDecision = new Map<string, number>();const codeNodeIds = new Map<string, "file" | "module">();- for (const e of codeEdges) {- if (decisionIds.has(e.decision_id)) codeNodeIds.set(e.node_id, e.link_type);+ const codeEdges: typeof allCodeEdges = [];+ let droppedCodeLinks = 0;+ for (const e of allCodeEdges) {+ if (!decisionIds.has(e.decision_id)) continue;+ const used = perDecision.get(e.decision_id) ?? 0;+ const isNewNode = !codeNodeIds.has(e.node_id);+ if (+ used >= MAX_CODE_LINKS_PER_DECISION ||+ (isNewNode && decisionIds.size + codeNodeIds.size >= MAX_LAYOUT_NODES)+ ) {+ droppedCodeLinks++;+ continue;+ }+ perDecision.set(e.decision_id, used + 1);+ if (isNewNode) codeNodeIds.set(e.node_id, e.link_type);+ codeEdges.push(e);}+ const truncationNote =+ droppedDecisions > 0 || droppedCodeLinks > 0+ ? `Too large to render fully — showing the top ${decisionNodes.length} decisions by impact` ++ (droppedCodeLinks > 0+ ? ` and up to ${MAX_CODE_LINKS_PER_DECISION} code links each (${droppedCodeLinks} links hidden).`+ : ".")+ : null;+const layoutNodes: C4LayoutNode[] = [- ...graph.nodes.map((n) => ({ id: n.id, ...DECISION_NODE_SIZE })),+ ...decisionNodes.map((n) => ({ id: n.id, ...DECISION_NODE_SIZE })),...[...codeNodeIds.keys()].map((id) => ({ id: `code:${id}`, ...CODE_NODE_SIZE })),];@@ -273,7 +326,7 @@ function useDecisionGraphLayout(graph: DecisionGraph | undefined, showCode: boolvoid computeC4Layout(layoutNodes, layoutEdges).then((positions) => {if (cancelled) return;const nodes: Node[] = [- ...graph.nodes.map((n) => {+ ...decisionNodes.map((n) => {const pos = positions.get(n.id) ?? { x: 0, y: 0 };return {id: n.id,@@ -314,7 +367,7 @@ function useDecisionGraphLayout(graph: DecisionGraph | undefined, showCode: bool})),];- setResult({ nodes, edges, loading: false });+ setResult({ nodes, edges, loading: false, truncationNote });});return () => {@@ -346,7 +399,7 @@ export function DecisionGraphView(props: DecisionGraphViewProps) {function DecisionGraphViewInner({ graph, isLoading, onSelectDecision }: DecisionGraphViewProps) {const [showCode, setShowCode] = useState(true);- const { nodes, edges, loading } = useDecisionGraphLayout(graph, showCode);+ const { nodes, edges, loading, truncationNote } = useDecisionGraphLayout(graph, showCode);const handleNodeClick: NodeMouseHandler = (_, node) => {if (node.type === "decision") onSelectDecision?.(node.id);@@ -391,6 +444,20 @@ function DecisionGraphViewInner({ graph, isLoading, onSelectDecision }: Decision</label></div>+ {truncationNote && (+ <div+ role="status"+ style={{+ padding: "4px 10px",+ borderBottom: "1px solid var(--color-border-default)",+ fontSize: 11,+ color: "var(--color-warning)",+ }}+ >+ {truncationNote}+ </div>+ )}+<div style={{ position: "relative", flex: 1, minHeight: 0 }}>{busy && nodes.length === 0 && <Centered text="Laying out decision graph…" />}{empty && <Centered text="No decision relationships to show." />}diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex f641534df..cca916bbf 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -1133,6 +1133,79 @@ export function buildDecisionAiPrompt({.join("\n");}+/**+ * Enforcement sibling of {@link buildDecisionAiPrompt}: where the+ * verification prompt asks "is this decision still true?", this one asks the+ * agent to bring non-conforming code into line with the decision — the+ * follow-through once a decision is confirmed.+ */+export function buildDecisionEnforcementAiPrompt({+ decision: d,+ flavor = "generic",+ repoName,+}: BuildDecisionPromptOptions): string {+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";+ const scope = [...(d.affected_modules ?? []), ...(d.affected_files ?? [])];++ const constraintList = [+ "Treat the decision text below as the standard; your job is conformance, not re-litigating whether the decision is right. If you find strong evidence the decision itself is wrong, stop and report that instead of enforcing it.",+ scope.length > 0+ ? "Start from the affected modules/files listed below, then follow the dependency graph to anything else that should obey this decision."+ : "First identify which parts of the codebase this decision governs, then audit them.",+ "Cite specific files/symbols for every violation — don't assert without a reference.",+ "Propose the minimal change that brings each violation into conformance; don't refactor beyond what the decision requires.",+ "Keep behavior identical except where the decision explicitly requires otherwise; call out any user-visible change.",+ ];++ const completionContract = [+ "1. A conformance audit: each governed file/module and whether it conforms or violates the decision, with evidence.",+ "2. For every violation, the concrete fix (file, symbol, and the change), ordered by impact.",+ "3. The fixes applied (or, if you can't safely change something, why, and what a human should do).",+ "4. Anything governed by the decision that you couldn't check, so nothing is silently skipped.",+ ];++ const closer =+ flavor === "claude-code-mcp"+ ? `Use \`get_why('${d.title.replace(/'/g, "")}')\` for the recorded rationale and \`get_context([${scope.slice(0, 3).map((s) => `'${s}'`).join(", ")}])\` for the governed code — repowise links decisions to graph nodes, so audit against that instead of guessing.`+ : "Read the decision below, open the code it governs, and make the code match the decision — with a cited audit trail for every change.";++ return [+ FLAVOR_PREAMBLE[flavor],+ "",+ `## Architectural decision to enforce${repoLine}`,+ "",+ bulletList([+ `Title: **${d.title}**`,+ `Status: ${d.status}`,+ scope.length > 0+ ? `Governs: ${scope.slice(0, 8).map((s) => `\`${s}\``).join(", ")}${scope.length > 8 ? `, +${scope.length - 8} more` : ""}`+ : null,+ ]),+ "",+ d.context ? ["## Context", "", d.context, ""].join("\n") : "",+ d.decision ? ["## Decision", "", d.decision, ""].join("\n") : "",+ d.rationale ? ["## Rationale", "", d.rationale, ""].join("\n") : "",+ d.consequences && d.consequences.length > 0+ ? ["## Consequences", "", bulletList(d.consequences), ""].join("\n")+ : "",+ "## Your task",+ "",+ "Audit the governed code for compliance with this decision, then fix every violation you find. This is an enforcement pass: the outcome should be code that conforms, not just a report.",+ "",+ "## Hard constraints",+ "",+ bulletList(constraintList),+ "",+ "## What I expect back",+ "",+ completionContract.join("\n"),+ "",+ closer,+ ]+ .filter((s) => s !== "")+ .join("\n");+}+// ─────────────────────────────────────────────────────────────────────// Commit review prompt (per commit)// ─────────────────────────────────────────────────────────────────────diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsxindex d693a5a44..365d83a19 100644--- a/packages/ui/src/health/health-file-drawer.tsx+++ b/packages/ui/src/health/health-file-drawer.tsx@@ -45,9 +45,11 @@ export interface HealthDrawerFinding {export interface HealthDrawerMetric {file_path: string;score: number;- max_ccn: number;- max_nesting: number;- nloc: number;+ /** Structural counters — null when the host has no metric row for the+ * file, so the drawer can say "not measured" instead of a misleading 0. */+ max_ccn: number | null;+ max_nesting: number | null;+ nloc: number | null;module: string | null;duplication_pct?: number | null;line_coverage_pct?: number | null;@@ -334,9 +336,9 @@ export function HealthFileDrawer({</span>)} />- <Stat label="Max CCN" value={<span className="text-base font-semibold tabular-nums">{metric.max_ccn}</span>} />- <Stat label="Nest" value={<span className="text-base font-semibold tabular-nums">{metric.max_nesting}</span>} />- <Stat label="NLOC" value={<span className="text-base font-semibold tabular-nums">{metric.nloc}</span>} />+ <Stat label="Max CCN" value={<MeasuredNum v={metric.max_ccn} />} />+ <Stat label="Nest" value={<MeasuredNum v={metric.max_nesting} />} />+ <Stat label="NLOC" value={<MeasuredNum v={metric.nloc} />} /><Stat label="Module" value={<span className="text-xs">{metric.module ?? "—"}</span>} /><Stat label="Tests" value={<span className="text-xs">{metric.has_test_file ? "Paired" : "None"}</span>} /><Stat label="Coverage" value={@@ -506,6 +508,22 @@ function FunctionFindingsGroup({);}+/** A structural counter that may genuinely be unmeasured — say so instead of+ * rendering a misleading 0. */+function MeasuredNum({ v }: { v: number | null }) {+ if (v == null) {+ return (+ <span+ className="text-xs text-[var(--color-text-tertiary)]"+ title="Not measured — no metric row is available for this file on this snapshot."+ >+ not measured+ </span>+ );+ }+ return <span className="text-base font-semibold tabular-nums">{v}</span>;+}+function Stat({ label, value }: { label: string; value: React.ReactNode }) {return (<div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">diff --git a/packages/ui/src/health/score-breakdown.tsx b/packages/ui/src/health/score-breakdown.tsxindex 726ebfb0e..953ee0071 100644--- a/packages/ui/src/health/score-breakdown.tsx+++ b/packages/ui/src/health/score-breakdown.tsx@@ -66,8 +66,16 @@ export function ScoreBreakdown({.map((c) => {const label =CATEGORY_LABEL[c.category as BiomarkerCategory] ?? c.category;- const cap = CATEGORY_CAP[c.category as BiomarkerCategory] ?? c.cap;- const pct = Math.min(100, (c.applied_deduction / Math.max(cap, 0.01)) * 100);+ // Only trust the glossary's caps for scaling the bar. A+ // payload-supplied cap for an unknown category is often just the+ // deduction echoed back at itself, which would render a+ // meaningless always-full bar.+ const knownCap = CATEGORY_CAP[c.category as BiomarkerCategory];+ const cap = knownCap ?? c.cap;+ const pct = Math.min(+ 100,+ (Math.abs(c.applied_deduction) / Math.max(Math.abs(cap), 0.01)) * 100,+ );return (<divkey={c.category}@@ -77,14 +85,26 @@ export function ScoreBreakdown({<span className="font-medium text-[var(--color-text-primary)]">{label}</span>- <span className="tabular-nums text-[var(--color-text-tertiary)]">+ <span+ className="cursor-help tabular-nums text-[var(--color-text-tertiary)]"+ title="The cap is the most this category is allowed to subtract from the 10-point score, no matter how many findings it has."+ >−{c.applied_deduction.toFixed(2)} / cap −{cap.toFixed(1)}- {c.capped ? <span className="ml-1 text-[var(--color-warning)]" title="Capped">(capped)</span> : null}+ {c.capped ? <span className="ml-1 text-[var(--color-warning)]" title="Raw deductions exceeded the cap; only the cap was subtracted.">(capped)</span> : null}</span></div><div className="mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-muted)]"><div- className="h-full bg-[var(--color-error)]/70"+ className={+ knownCap != null+ ? "h-full bg-[var(--color-error)]/70"+ : "h-full bg-[var(--color-text-tertiary)]/40"+ }+ title={+ knownCap == null+ ? "No defined cap for this category — bar scale is approximate."+ : undefined+ }style={{ width: `${pct}%` }}/></div>diff --git a/packages/ui/src/stats/index.ts b/packages/ui/src/stats/index.tsindex 292debe80..6a1cf969c 100644--- a/packages/ui/src/stats/index.ts+++ b/packages/ui/src/stats/index.ts@@ -1,4 +1,10 @@export { SizeClassHero } from "./size-class-hero";-export { StatCallout, type StatCalloutProps, type CalloutTone } from "./stat-callout";+export {+ StatCallout,+ NLOC_HINT,+ AGENT_PCT_HINT,+ type StatCalloutProps,+ type CalloutTone,+} from "./stat-callout";export { SuperlativesGrid } from "./superlatives-grid";export { ActivityTrendChart } from "./activity-trend-chart";diff --git a/packages/ui/src/stats/size-class-hero.tsx b/packages/ui/src/stats/size-class-hero.tsxindex 2858392bf..b27b97211 100644--- a/packages/ui/src/stats/size-class-hero.tsx+++ b/packages/ui/src/stats/size-class-hero.tsx@@ -9,6 +9,7 @@ import {} from "lucide-react";import type { StatsScale } from "@repowise-dev/types/stats";import { formatNumber, formatLOC } from "../lib/format";+import { NLOC_HINT } from "./stat-callout";const SIZE_ICON: Record<string, React.ComponentType<{ className?: string }>> = {Seedling: Sprout,@@ -23,6 +24,8 @@ const SIZE_ICON: Record<string, React.ComponentType<{ className?: string }>> = {interface HeroFigure {label: string;value: string;+ /** Longer clarification shown as a native hover tooltip. */+ hint?: string;}interface SizeClassHeroProps {@@ -40,7 +43,7 @@ export function SizeClassHero({ scale, repoName }: SizeClassHeroProps) {const Icon = SIZE_ICON[scale.size_class.name] ?? Building2;const figures: HeroFigure[] = [- { label: "Lines of code", value: formatLOC(scale.total_nloc) },+ { label: "Lines of code", value: formatLOC(scale.total_nloc), hint: NLOC_HINT },{ label: "Files", value: formatNumber(scale.file_count) },{ label: "Symbols", value: formatNumber(scale.symbol_count) },{ label: "Languages", value: formatNumber(scale.language_count) },@@ -80,7 +83,8 @@ export function SizeClassHero({ scale, repoName }: SizeClassHeroProps) {{figures.map((f) => (<divkey={f.label}- className="rounded-xl border border-[var(--color-border-subtle,var(--color-border-default))] bg-[var(--color-bg-surface)]/70 px-4 py-3 backdrop-blur-sm"+ title={f.hint}+ className={`rounded-xl border border-[var(--color-border-subtle,var(--color-border-default))] bg-[var(--color-bg-surface)]/70 px-4 py-3 backdrop-blur-sm${f.hint ? " cursor-help" : ""}`}><p className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)] sm:text-3xl">{f.value}diff --git a/packages/ui/src/stats/stat-callout.tsx b/packages/ui/src/stats/stat-callout.tsxindex f33160a71..948f477c7 100644--- a/packages/ui/src/stats/stat-callout.tsx+++ b/packages/ui/src/stats/stat-callout.tsx@@ -3,6 +3,13 @@ import { cn } from "../lib/cn";export type CalloutTone = "default" | "accent" | "success" | "warning" | "info";+// Canonical clarifications for the two most-misread stats, shared by every+// surface that shows them (stats tabs, overview teaser, size-class hero).+export const NLOC_HINT =+ "Lines of code in the repo today: non-blank, non-comment lines, excluding lockfiles, generated and vendored files. Not a historical total — deleted code doesn't count.";+export const AGENT_PCT_HINT =+ "Share of commits with a verifiable agent signature: known bot identities, agent commit footers, or Co-authored-by agent trailers. Squash merges that drop trailers and agents committing under a human git identity can't be detected, so the true share may be higher.";+const TONE_VALUE: Record<CalloutTone, string> = {default: "text-[var(--color-text-primary)]",accent: "text-[var(--color-accent-primary)]",@@ -18,6 +25,8 @@ export interface StatCalloutProps {value: React.ReactNode;/** One-line context shown under the figure. */sub?: React.ReactNode;+ /** Longer clarification shown as a native hover tooltip on the card. */+ hint?: string;icon?: React.ReactNode;tone?: CalloutTone;className?: string;@@ -32,14 +41,17 @@ export function StatCallout({label,value,sub,+ hint,icon,tone = "default",className,}: StatCalloutProps) {return (<div+ title={hint}className={cn("rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4",+ hint && "cursor-help",className,)}>diff --git a/packages/web/src/components/overview/stats-teaser-card.tsx b/packages/web/src/components/overview/stats-teaser-card.tsxindex 73ed218d3..eb77557ce 100644--- a/packages/web/src/components/overview/stats-teaser-card.tsx+++ b/packages/web/src/components/overview/stats-teaser-card.tsx@@ -3,6 +3,7 @@ import { BarChart3, ArrowRight, Bot } from "lucide-react";import type { StatsHighlights } from "@repowise-dev/types/stats";import { Card } from "@repowise-dev/ui/ui/card";import { formatLOC, formatNumber, formatAgeDays } from "@repowise-dev/ui/lib/format";+import { NLOC_HINT, AGENT_PCT_HINT } from "@repowise-dev/ui/stats";interface StatsTeaserCardProps {repoId: string;@@ -14,8 +15,8 @@ interface StatsTeaserCardProps {export function StatsTeaserCard({ repoId, data }: StatsTeaserCardProps) {const { scale, activity } = data;- const figures: { label: string; value: string }[] = [- { label: "Lines", value: formatLOC(scale.total_nloc) },+ const figures: { label: string; value: string; hint?: string }[] = [+ { label: "Lines of code", value: formatLOC(scale.total_nloc), hint: NLOC_HINT },{ label: "Commits", value: formatNumber(activity.total_commits) },{label: "Age",@@ -48,7 +49,7 @@ export function StatsTeaserCard({ repoId, data }: StatsTeaserCardProps) {<div className="mt-3 grid grid-cols-3 gap-2">{figures.map((f) => (- <div key={f.label}>+ <div key={f.label} title={f.hint} className={f.hint ? "cursor-help" : undefined}><p className="text-base font-semibold tabular-nums text-[var(--color-text-primary)]">{f.value}</p>@@ -60,9 +61,12 @@ export function StatsTeaserCard({ repoId, data }: StatsTeaserCardProps) {</div>{activity.total_commits > 0 && (- <p className="mt-3 flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">+ <p+ title={AGENT_PCT_HINT}+ className="mt-3 flex cursor-help items-center gap-1.5 text-xs text-[var(--color-text-secondary)]"+ ><Bot className="h-3.5 w-3.5 text-[var(--color-info)]" />- {activity.agent_pct}% of commits agent-authored+ {activity.agent_pct}% of commits carry a verifiable agent signature</p>)}</Link>diff --git a/packages/web/src/components/stats/by-the-numbers-tab.tsx b/packages/web/src/components/stats/by-the-numbers-tab.tsxindex 65a2cab6e..90d02690e 100644--- a/packages/web/src/components/stats/by-the-numbers-tab.tsx+++ b/packages/web/src/components/stats/by-the-numbers-tab.tsx@@ -1,6 +1,12 @@import { Bot, CalendarClock, Users, ShieldCheck, Trash2, HeartPulse } from "lucide-react";import type { StatsHighlights } from "@repowise-dev/types/stats";-import { SizeClassHero, StatCallout, SuperlativesGrid } from "@repowise-dev/ui/stats";+import {+ SizeClassHero,+ StatCallout,+ SuperlativesGrid,+ NLOC_HINT,+ AGENT_PCT_HINT,+} from "@repowise-dev/ui/stats";import { formatNumber, formatLOC, formatAgeDays, formatDate } from "@repowise-dev/ui/lib/format";export function ByTheNumbersTab({ data }: { data: StatsHighlights }) {@@ -19,7 +25,8 @@ export function ByTheNumbersTab({ data }: { data: StatsHighlights }) {icon={<Bot className="h-4 w-4" />}sub={`${formatNumber(activity.agent_commits)} of ${formatNumber(activity.total_commits,- )} commits written by agents`}+ )} commits carry a verifiable agent signature`}+ hint={AGENT_PCT_HINT}/><StatCalloutlabel="Project age"@@ -60,11 +67,12 @@ export function ByTheNumbersTab({ data }: { data: StatsHighlights }) {<div className="grid grid-cols-1 gap-3 sm:grid-cols-3"><StatCallout- label="Total lines"+ label="Lines of code"value={formatLOC(scale.total_nloc)}- sub={`${formatNumber(scale.symbol_count)} symbols across ${formatNumber(+ sub={`in the repo today · ${formatNumber(scale.symbol_count)} symbols across ${formatNumber(scale.module_count,)} modules`}+ hint={NLOC_HINT}/><StatCalloutlabel="Knowledge captured"diff --git a/packages/web/src/components/stats/growth-tab.tsx b/packages/web/src/components/stats/growth-tab.tsxindex e0c6629a7..b7173bdc6 100644--- a/packages/web/src/components/stats/growth-tab.tsx+++ b/packages/web/src/components/stats/growth-tab.tsx@@ -1,5 +1,5 @@import type { StatsHighlights } from "@repowise-dev/types/stats";-import { ActivityTrendChart, StatCallout } from "@repowise-dev/ui/stats";+import { ActivityTrendChart, StatCallout, AGENT_PCT_HINT } from "@repowise-dev/ui/stats";import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";import { formatNumber, formatDate } from "@repowise-dev/ui/lib/format";@@ -44,7 +44,8 @@ export function GrowthTab({ data }: { data: StatsHighlights }) {label="Agent commits"value={`${activity.agent_pct}%`}tone="info"- sub={`${formatNumber(activity.agent_commits)} agent-authored`}+ sub={`${formatNumber(activity.agent_commits)} commits with verifiable agent signatures`}+ hint={AGENT_PCT_HINT}/></div>