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.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
feat(ui): the Atlas Dashboard — graph-derived metrics with drill-down
Martin Vogel16b90077dbf1
diff --git a/Makefile.cbm b/Makefile.cbmindex d8f43fe6c..431872f95 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -390,6 +390,7 @@ UI_SRCS = \src/ui/layout_regions.c \src/ui/atlas_api.c \src/ui/atlas_flows.c \+ src/ui/atlas_metrics.c \src/ui/httpd.c \src/ui/embedded_stub.cdiff --git a/graph-ui/src/App.tsx b/graph-ui/src/App.tsxindex 6d21ad144..ad18efb81 100644--- a/graph-ui/src/App.tsx+++ b/graph-ui/src/App.tsx@@ -7,6 +7,7 @@ import { ModulesTab } from "./components/ModulesTab";import { SymbolTab } from "./components/SymbolTab";import { FlowsTab } from "./components/FlowsTab";import { ChangesTab } from "./components/ChangesTab";+import { DashboardTab } from "./components/DashboardTab";import { CommandK } from "./components/CommandK";import {PromptBasketProvider,@@ -21,13 +22,14 @@ const TAB_IDS: TabId[] = ["graph","flows","changes",+ "dashboard","symbol","stats","control",];/* Tabs that need a selected project. "symbol" is reachable only via links. */-const PROJECT_TABS: TabId[] = ["overview", "modules", "graph", "flows", "changes"];+const PROJECT_TABS: TabId[] = ["overview", "modules", "graph", "flows", "changes", "dashboard"];interface RouteState {tab: TabId;@@ -137,6 +139,7 @@ export function App() {{ id: "graph", label: "Galaxy" },{ id: "flows", label: "Flows" },{ id: "changes", label: "Changes" },+ { id: "dashboard", label: "Dashboard" },{ id: "stats", label: t.tabs.projects },{ id: "control", label: t.tabs.control },];@@ -251,6 +254,11 @@ export function App() {/>) : activeTab === "changes" && selectedProject ? (<ChangesTab project={selectedProject} onOpenSymbol={openSymbol} />+ ) : activeTab === "dashboard" && selectedProject ? (+ <DashboardTab+ project={selectedProject}+ onOpenSymbol={(ref) => openSymbol(ref)}+ />) : activeTab === "symbol" && selectedProject && symbolRef ? (<SymbolTabproject={selectedProject}diff --git a/graph-ui/src/components/DashboardTab.tsx b/graph-ui/src/components/DashboardTab.tsxnew file mode 100644index 000000000..ce332869b--- /dev/null+++ b/graph-ui/src/components/DashboardTab.tsx@@ -0,0 +1,309 @@+/* Dashboard — the project's numbers with the code behind them one click+ * away. No composite health score: the cards are the score. Everything is+ * derived from the graph (and one bounded git-log pass); nothing here asks+ * a model anything. */+import { useEffect, useState } from "react";+import { ScrollArea } from "@/components/ui/scroll-area";++interface MetricEntry {+ qn?: string;+ name?: string;+ file?: string;+ value: number;+}++interface MetricsPayload {+ generated_from: string;+ totals: {+ callables: number;+ dead: number;+ tested_symbols: number;+ similar_edges: number;+ missed_files: number;+ exported: number;+ documented_exported: number;+ avg_complexity: number;+ };+ certainty: { calls: number; call_reference: number; usage: number };+ complexity_hist: number[];+ lines_hist: number[];+ top_complex: MetricEntry[];+ top_cognitive: MetricEntry[];+ top_long: MetricEntry[];+ top_churn: MetricEntry[];+ top_churn_complex: MetricEntry[];+ churn_available: boolean;+ history: {+ indexed_at: string;+ callables: number;+ dead: number;+ avg_complexity: number;+ tested: number;+ usage_share: number;+ }[];+}++interface DashboardTabProps {+ project: string;+ onOpenSymbol: (ref: { qn: string }) => void;+}++const CPLX_LABELS = ["1", "2–5", "6–10", "11–20", "21–50", ">50"];+const LINE_LABELS = ["≤10", "≤30", "≤60", "≤120", ">120"];++function Histogram({ values, labels }: { values: number[]; labels: string[] }) {+ const max = Math.max(1, ...values);+ return (+ <div className="flex items-end gap-1.5 h-[72px] mt-2">+ {values.map((value, index) => (+ <div key={index} className="flex-1 flex flex-col items-center gap-1 min-w-0">+ <span className="text-[9px] tabular-nums text-foreground/30">+ {value.toLocaleString("en-US")}+ </span>+ <div+ className="w-full rounded-sm bg-primary/40"+ style={{ height: `${Math.max(2, (value / max) * 46)}px` }}+ />+ <span className="text-[8.5px] text-foreground/25">{labels[index]}</span>+ </div>+ ))}+ </div>+ );+}++function Sparkline({ points }: { points: number[] }) {+ if (points.length < 2) return null;+ const max = Math.max(...points);+ const min = Math.min(...points);+ const span = max - min || 1;+ const coords = points+ .map(+ (point, index) =>+ `${(index / (points.length - 1)) * 100},${28 - ((point - min) / span) * 24}`,+ )+ .join(" ");+ return (+ <svg viewBox="0 0 100 30" className="w-full h-[30px] mt-1" preserveAspectRatio="none">+ <polyline points={coords} fill="none" stroke="currentColor" strokeWidth="1.5"+ className="text-primary/60" vectorEffect="non-scaling-stroke" />+ </svg>+ );+}++function StatCard({+ label,+ value,+ sub,+ tone,+ trend,+}: {+ label: string;+ value: string;+ sub?: string;+ tone?: "warn" | "crit";+ trend?: number[];+}) {+ return (+ <div className="bg-white/[0.02] border border-border/40 rounded-xl p-4 min-w-0">+ <p className="text-[9px] uppercase tracking-widest text-foreground/30">{label}</p>+ <p+ className={`text-[22px] font-semibold tabular-nums mt-1 ${+ tone === "crit"+ ? "text-red-300/90"+ : tone === "warn"+ ? "text-amber-300/90"+ : "text-foreground/90"+ }`}+ >+ {value}+ </p>+ {sub && <p className="text-[10px] text-foreground/30 mt-0.5">{sub}</p>}+ {trend && trend.length > 1 && <Sparkline points={trend} />}+ </div>+ );+}++function TopList({+ title,+ entries,+ unit,+ onOpenSymbol,+}: {+ title: string;+ entries: MetricEntry[];+ unit: string;+ onOpenSymbol?: (ref: { qn: string }) => void;+}) {+ return (+ <div className="bg-white/[0.02] border border-border/40 rounded-xl p-4">+ <p className="text-[10px] uppercase tracking-widest text-foreground/30 mb-2">{title}</p>+ <div className="space-y-px">+ {entries.map((entry, index) => {+ const label = entry.name ?? entry.file ?? "?";+ const clickable = entry.qn && onOpenSymbol;+ const Row = clickable ? "button" : "div";+ return (+ <Row+ key={`${label}-${index}`}+ onClick={clickable ? () => onOpenSymbol!({ qn: entry.qn! }) : undefined}+ className={`flex items-center gap-2 w-full text-left py-[3px] ${+ clickable ? "group cursor-pointer" : ""+ }`}+ >+ <span+ className={`text-[11px] font-mono truncate flex-1 ${+ clickable+ ? "text-foreground/60 group-hover:text-primary transition-colors"+ : "text-foreground/55"+ }`}+ title={entry.qn ?? entry.file}+ >+ {label}+ </span>+ <span className="text-[10px] tabular-nums text-foreground/35 shrink-0">+ {entry.value.toLocaleString("en-US")} {unit}+ </span>+ </Row>+ );+ })}+ {entries.length === 0 && <p className="text-[11px] text-foreground/25">None.</p>}+ </div>+ </div>+ );+}++export function DashboardTab({ project, onOpenSymbol }: DashboardTabProps) {+ const [metrics, setMetrics] = useState<MetricsPayload | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ setMetrics(null);+ setError(null);+ fetch(`/api/metrics?${new URLSearchParams({ project })}`)+ .then(async (res) => {+ if (!res.ok) throw new Error((await res.json().catch(() => null))?.error ?? `HTTP ${res.status}`);+ return res.json();+ })+ .then((payload) => {+ if (!cancelled) setMetrics(payload);+ })+ .catch((err) => {+ if (!cancelled) setError(err instanceof Error ? err.message : "failed");+ });+ return () => {+ cancelled = true;+ };+ }, [project]);++ if (error) {+ return (+ <div className="flex items-center justify-center h-full">+ <p className="text-red-400/80 text-sm">{error}</p>+ </div>+ );+ }+ if (!metrics) {+ return (+ <div className="flex items-center justify-center h-full">+ <p className="text-white/30 text-sm">Measuring…</p>+ </div>+ );+ }++ const { totals, certainty } = metrics;+ const callish = certainty.calls + certainty.call_reference + certainty.usage;+ const resolvedShare = callish > 0 ? (certainty.calls + certainty.call_reference) / callish : 0;+ const docShare = totals.exported > 0 ? totals.documented_exported / totals.exported : 0;+ const testedShare = totals.callables > 0 ? totals.tested_symbols / totals.callables : 0;+ const history = metrics.history ?? [];++ return (+ <ScrollArea className="h-full">+ <div className="max-w-[1200px] mx-auto px-6 py-6">+ <p className="text-[10px] text-foreground/25 font-mono mb-4">+ computed from index {metrics.generated_from}+ {history.length > 1 && ` · trends across ${history.length} index runs`}+ </p>++ {/* Cards */}+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">+ <StatCard+ label="Callables"+ value={totals.callables.toLocaleString("en-US")}+ sub={`avg complexity ${totals.avg_complexity.toFixed(1)}`}+ trend={history.map((entry) => entry.callables)}+ />+ <StatCard+ label="Call resolution"+ 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)}+ />+ <StatCard+ label="Dead candidates"+ 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)}+ />+ <StatCard+ label="Tested symbols"+ value={`${(testedShare * 100).toFixed(0)}%`}+ sub={`${totals.tested_symbols.toLocaleString("en-US")} with TESTS edges`}+ trend={history.map((entry) => entry.tested)}+ />+ <StatCard+ label="Documented exports"+ value={`${(docShare * 100).toFixed(0)}%`}+ sub={`${totals.documented_exported.toLocaleString("en-US")} of ${totals.exported.toLocaleString("en-US")} exported`}+ tone={docShare < 0.3 ? "warn" : undefined}+ />+ <StatCard+ label="Near-clone edges"+ value={totals.similar_edges.toLocaleString("en-US")}+ sub="SIMILAR_TO (MinHash)"+ />+ <StatCard+ label="Files not fully indexed"+ value={totals.missed_files.toLocaleString("en-US")}+ sub="the missed skeleton in the galaxy"+ tone={totals.missed_files > 0 ? "warn" : undefined}+ />+ <div className="bg-white/[0.02] border border-border/40 rounded-xl p-4">+ <p className="text-[9px] uppercase tracking-widest text-foreground/30">+ Complexity distribution+ </p>+ <Histogram values={metrics.complexity_hist} labels={CPLX_LABELS} />+ </div>+ </div>++ <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">+ <div className="bg-white/[0.02] border border-border/40 rounded-xl p-4">+ <p className="text-[9px] uppercase tracking-widest text-foreground/30">+ Function length (lines)+ </p>+ <Histogram values={metrics.lines_hist} labels={LINE_LABELS} />+ </div>+ <TopList+ title={+ metrics.churn_available+ ? "Where the bugs live — churn × complexity (1y)"+ : "Churn unavailable (no git history readable)"+ }+ entries={metrics.top_churn_complex}+ unit="score"+ />+ </div>++ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">+ <TopList title="Most complex" entries={metrics.top_complex} unit="cyclo" onOpenSymbol={onOpenSymbol} />+ <TopList title="Hardest to follow" entries={metrics.top_cognitive} unit="cog" onOpenSymbol={onOpenSymbol} />+ <TopList title="Longest" entries={metrics.top_long} unit="lines" onOpenSymbol={onOpenSymbol} />+ <TopList title="Most churned files (1y)" entries={metrics.top_churn} unit="commits" />+ </div>+ </div>+ </ScrollArea>+ );+}diff --git a/graph-ui/src/lib/types.ts b/graph-ui/src/lib/types.tsindex cf4317d7f..76df89c33 100644--- a/graph-ui/src/lib/types.ts+++ b/graph-ui/src/lib/types.ts@@ -119,6 +119,7 @@ export type TabId =| "graph"| "flows"| "changes"+ | "dashboard"| "symbol"| "stats"| "control";diff --git a/graph-ui/tsconfig.tsbuildinfo b/graph-ui/tsconfig.tsbuildinfoindex d1716ee91..255a8b2a1 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/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/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/promptbasket.tsx","./src/components/regionpanel.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/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/firstread.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"],"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/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/promptbasket.tsx","./src/components/regionpanel.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/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/firstread.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"],"version":"5.9.3"}\ No newline at end of filediff --git a/src/ui/atlas.h b/src/ui/atlas.hindex 5774deb51..48670614d 100644--- a/src/ui/atlas.h+++ b/src/ui/atlas.h@@ -36,6 +36,15 @@ char *cbm_atlas_flow_json(cbm_store_t *store, const char *project, int flow_id);/* Drop the flows cache (tests). */void cbm_atlas_flows_cache_clear(void);+/* ── Dashboard metrics (GET /api/metrics) ─────────────────────────+ * Graph-derived metrics with drill-down lists: complexity/length+ * histograms and tops (from pass_complexity's stored numbers), edge+ * certainty, dead code, tests/duplication/missed counts, per-file churn+ * from a bounded `git log` (zero indexing cost), churn×complexity, and a+ * per-index history sidecar for trends. Cached per (project, indexed_at). */+char *cbm_atlas_metrics_json(cbm_store_t *store, const char *project);+void cbm_atlas_metrics_cache_clear(void);+/* ── Region lookups (layout_regions.c) ────────────────────────────* Cache-backed; computing on first use. name_out (optional) receives a* heap copy the caller frees. Returns region id or -1. */diff --git a/src/ui/atlas_metrics.c b/src/ui/atlas_metrics.cnew file mode 100644index 000000000..bc4387ab4--- /dev/null+++ b/src/ui/atlas_metrics.c@@ -0,0 +1,539 @@+/*+ * atlas_metrics.c — the CBM Atlas Dashboard: graph-derived metrics with+ * drill-down, computed from data the index already stores plus one bounded+ * `git log` pass — ZERO cost added to indexing time.+ *+ * Tier 0 (stored): cyclomatic + cognitive complexity, lines and flags per+ * callable (pass_complexity), edge certainty (CALLS vs CALL_REFERENCE vs+ * USAGE), dead code, TESTS linkage, SIMILAR_TO duplication, missed files.+ * Tier 1 (computed here, cached): per-file churn from `git log` (same+ * bounds as pass_githistory: 1 year, ≤10k commits), churn × complexity.+ * History: one snapshot per indexed_at appended to a sidecar JSONL in the+ * cache dir, so the dashboard can show trends across reindexes.+ */+#include "foundation/constants.h"+#include "ui/atlas.h"+#include "foundation/compat_fs.h"+#include "foundation/hash_table.h"+#include "foundation/str_util.h"+#include "foundation/workspace.h"++#include <sqlite3.h>+#include <yyjson/yyjson.h>++#include <math.h>+#include <pthread.h>+#include <stdbool.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++enum {+ MX_TOP_N = 10, /* entries per drill-down list */+ MX_HISTORY_MAX = 60, /* snapshots served to the dashboard */+ MX_CHURN_MIN_CPLX = 10, /* churn×complexity: only genuinely complex files */+};++/* Complexity histogram bucket upper bounds (inclusive); last is open. */+static const int MX_CPLX_BUCKETS[] = {1, 5, 10, 20, 50};+static const int MX_LINE_BUCKETS[] = {10, 30, 60, 120};++typedef struct {+ char *qn;+ char *name;+ char *file;+ long long value;+} mx_entry_t;++typedef struct {+ mx_entry_t items[MX_TOP_N];+ int count;+} mx_top_t;++/* Keep the MX_TOP_N largest values (stable for ties: first seen wins). */+static void mx_top_offer(mx_top_t *top, const char *qn, const char *name, const char *file,+ long long value) {+ int pos = top->count < MX_TOP_N ? top->count : MX_TOP_N;+ while (pos > 0 && top->items[pos - 1].value < value)+ pos--;+ if (pos >= MX_TOP_N)+ return;+ mx_entry_t incoming;+ incoming.qn = qn ? strdup(qn) : NULL;+ incoming.name = name ? strdup(name) : NULL;+ incoming.file = file ? strdup(file) : NULL;+ incoming.value = value;+ mx_entry_t last = {0};+ if (top->count == MX_TOP_N) {+ last = top->items[MX_TOP_N - 1];+ } else {+ top->count++;+ }+ for (int i = top->count - 1; i > pos; i--)+ top->items[i] = top->items[i - 1];+ top->items[pos] = incoming;+ free(last.qn);+ free(last.name);+ free(last.file);+}++static void mx_top_free(mx_top_t *top) {+ for (int i = 0; i < top->count; i++) {+ free(top->items[i].qn);+ free(top->items[i].name);+ free(top->items[i].file);+ }+ top->count = 0;+}++static void mx_top_json(yyjson_mut_doc *doc, yyjson_mut_val *root, const char *field,+ const mx_top_t *top) {+ yyjson_mut_val *arr = yyjson_mut_arr(doc);+ for (int i = 0; i < top->count; i++) {+ yyjson_mut_val *obj = yyjson_mut_obj(doc);+ if (top->items[i].qn)+ yyjson_mut_obj_add_strcpy(doc, obj, "qn", top->items[i].qn);+ if (top->items[i].name)+ yyjson_mut_obj_add_strcpy(doc, obj, "name", top->items[i].name);+ if (top->items[i].file)+ yyjson_mut_obj_add_strcpy(doc, obj, "file", top->items[i].file);+ yyjson_mut_obj_add_int(doc, obj, "value", top->items[i].value);+ yyjson_mut_arr_append(arr, obj);+ }+ yyjson_mut_obj_add_val(doc, root, field, arr);+}++/* ── Cache ────────────────────────────────────────────────────── */++typedef struct {+ char key[1152];+ char *json;+} mx_cache_t;++static mx_cache_t g_mx_cache;+static pthread_mutex_t g_mx_mu = PTHREAD_MUTEX_INITIALIZER;++void cbm_atlas_metrics_cache_clear(void) {+ pthread_mutex_lock(&g_mx_mu);+ free(g_mx_cache.json);+ memset(&g_mx_cache, 0, sizeof(g_mx_cache));+ pthread_mutex_unlock(&g_mx_mu);+}++static void mx_project_stamp(cbm_store_t *store, const char *project, char *stamp, size_t cap,+ char *root_path, size_t root_cap) {+ stamp[0] = '\0';+ if (root_path)+ root_path[0] = '\0';+ struct sqlite3 *db = cbm_store_get_db(store);+ sqlite3_stmt *st = NULL;+ if (db && sqlite3_prepare_v2(db, "SELECT indexed_at, root_path FROM projects WHERE name=?1",+ -1, &st, NULL) == SQLITE_OK) {+ sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);+ if (sqlite3_step(st) == SQLITE_ROW) {+ const char *t = (const char *)sqlite3_column_text(st, 0);+ const char *r = (const char *)sqlite3_column_text(st, 1);+ if (t)+ snprintf(stamp, cap, "%s", t);+ if (r && root_path)+ snprintf(root_path, root_cap, "%s", r);+ }+ sqlite3_finalize(st);+ }+}++/* ── Churn: one bounded `git log` pass, cached with everything else ── */++typedef struct {+ CBMHashTable *counts; /* file_path → (intptr_t)count; keys owned by list */+ char **keys;+ int key_count;+ int key_cap;+} mx_churn_t;++static void mx_churn_scan(const char *root_path, mx_churn_t *churn) {+ if (!root_path || !root_path[0] || !cbm_validate_shell_path_arg(root_path))+ return;+ churn->counts = cbm_ht_create(1024);+ if (!churn->counts)+ return;+#ifdef _WIN32+ const char *null_dev = "NUL";+#else+ const char *null_dev = "/dev/null";+#endif+ char cmd[CBM_SZ_2K];+ snprintf(cmd, sizeof(cmd),+ "git -C \"%s\" log --name-only --pretty=format: --since=\"1 year ago\" "+ "--max-count=10000 2>%s",+ root_path, null_dev);+ FILE *fp = cbm_popen(cmd, "r");+ if (!fp)+ return;+ char line[CBM_SZ_1K];+ while (fgets(line, sizeof(line), fp)) {+ size_t len = strlen(line);+ while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r'))+ line[--len] = '\0';+ if (len == 0)+ continue;+ const char *canon = cbm_ht_get_key(churn->counts, line);+ if (!canon) {+ if (churn->key_count >= churn->key_cap) {+ int nc = churn->key_cap ? churn->key_cap * 2 : 1024;+ char **grown = realloc(churn->keys, (size_t)nc * sizeof(char *));+ if (!grown)+ break;+ churn->keys = grown;+ churn->key_cap = nc;+ }+ churn->keys[churn->key_count] = strdup(line);+ if (!churn->keys[churn->key_count])+ break;+ canon = churn->keys[churn->key_count];+ churn->key_count++;+ }+ intptr_t count = (intptr_t)cbm_ht_get(churn->counts, canon);+ cbm_ht_set(churn->counts, canon, (void *)(count + 1));+ }+ cbm_pclose(fp);+}++static void mx_churn_free(mx_churn_t *churn) {+ cbm_ht_free(churn->counts);+ for (int i = 0; i < churn->key_count; i++)+ free(churn->keys[i]);+ free(churn->keys);+ memset(churn, 0, sizeof(*churn));+}++/* ── History sidecar (JSONL, one snapshot per indexed_at) ─────── */++static void mx_history_path(const char *project, char *out, size_t cap) {+ const char *cache = cbm_workspace_cache_dir();+ snprintf(out, cap, "%s/atlas-metrics-%s.jsonl", cache ? cache : ".", project);+}++static void mx_history_append_and_emit(yyjson_mut_doc *doc, yyjson_mut_val *root,+ const char *project, const char *stamp,+ long long callables, long long dead, double avg_cplx,+ long long tested, long long usage_edges,+ long long callish_edges) {+ if (!cbm_validate_project_name(project))+ return;+ char path[CBM_SZ_1K];+ mx_history_path(project, path, sizeof(path));++ /* Read existing lines (bounded). */+ char *lines[MX_HISTORY_MAX];+ int line_count = 0;+ bool stamp_present = false;+ FILE *fp = cbm_fopen(path, "r");+ if (fp) {+ char buf[CBM_SZ_2K];+ while (fgets(buf, sizeof(buf), fp)) {+ if (strstr(buf, stamp))+ stamp_present = true;+ if (line_count == MX_HISTORY_MAX) {+ free(lines[0]);+ memmove(lines, lines + 1, (size_t)(MX_HISTORY_MAX - 1) * sizeof(char *));+ line_count--;+ }+ lines[line_count] = strdup(buf);+ if (!lines[line_count])+ break;+ line_count++;+ }+ fclose(fp);+ }++ /* Append this index generation once. */+ if (!stamp_present && stamp[0]) {+ FILE *out = cbm_fopen(path, "a");+ if (out) {+ fprintf(out,+ "{\"indexed_at\":\"%s\",\"callables\":%lld,\"dead\":%lld,"+ "\"avg_complexity\":%.2f,\"tested\":%lld,\"usage_share\":%.4f}\n",+ stamp, callables, dead, avg_cplx, tested,+ callish_edges > 0 ? (double)usage_edges / (double)callish_edges : 0.0);+ fclose(out);+ }+ }++ yyjson_mut_val *history = yyjson_mut_arr(doc);+ for (int i = 0; i < line_count; i++) {+ yyjson_doc *entry = yyjson_read(lines[i], strlen(lines[i]), 0);+ if (entry) {+ yyjson_mut_val *copy = yyjson_val_mut_copy(doc, yyjson_doc_get_root(entry));+ if (copy)+ yyjson_mut_arr_append(history, copy);+ yyjson_doc_free(entry);+ }+ free(lines[i]);+ }+ yyjson_mut_obj_add_val(doc, root, "history", history);+}++/* ── Build ────────────────────────────────────────────────────── */++static char *mx_build_json(cbm_store_t *store, const char *project, const char *stamp,+ const char *root_path) {+ struct sqlite3 *db = cbm_store_get_db(store);+ if (!db)+ return NULL;++ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root);+ yyjson_mut_obj_add_strcpy(doc, root, "generated_from", stamp);++ /* A. Callable scan: histograms, docstring coverage, top lists, per-file+ * max complexity for the churn join. */+ long long callables = 0, cplx_sum = 0, documented_exported = 0, exported = 0;+ long long cplx_hist[6] = {0};+ long long line_hist[5] = {0};+ mx_top_t top_complex = {0}, top_cognitive = {0}, top_long = {0};+ CBMHashTable *file_cplx = cbm_ht_create(1024); /* file → max complexity */+ char **file_keys = NULL;+ int file_key_count = 0, file_key_cap = 0;++ sqlite3_stmt *st = NULL;+ const char *scan_sql =+ "SELECT name, qualified_name, file_path, "+ "COALESCE(json_extract(properties,'$.complexity'),0), "+ "COALESCE(json_extract(properties,'$.cognitive'),0), "+ "COALESCE(json_extract(properties,'$.lines'),0), "+ "CASE WHEN json_extract(properties,'$.docstring') IS NOT NULL THEN 1 ELSE 0 END, "+ "COALESCE(json_extract(properties,'$.is_exported'),0) "+ "FROM nodes WHERE project=?1 AND label IN (" CBM_SQL_CALLABLE_LABELS ")";+ if (sqlite3_prepare_v2(db, scan_sql, -1, &st, NULL) == SQLITE_OK) {+ sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);+ while (sqlite3_step(st) == SQLITE_ROW) {+ const char *name = (const char *)sqlite3_column_text(st, 0);+ const char *qn = (const char *)sqlite3_column_text(st, 1);+ const char *file = (const char *)sqlite3_column_text(st, 2);+ long long cplx = sqlite3_column_int64(st, 3);+ long long cognitive = sqlite3_column_int64(st, 4);+ long long lines = sqlite3_column_int64(st, 5);+ bool documented = sqlite3_column_int(st, 6) != 0;+ bool is_exported = sqlite3_column_int(st, 7) != 0;+ callables++;+ cplx_sum += cplx;+ int bucket = 0;+ while (bucket < 5 && cplx > MX_CPLX_BUCKETS[bucket])+ bucket++;+ cplx_hist[bucket]++;+ bucket = 0;+ while (bucket < 4 && lines > MX_LINE_BUCKETS[bucket])+ bucket++;+ line_hist[bucket]++;+ if (is_exported) {+ exported++;+ if (documented)+ documented_exported++;+ }+ if (cplx > 1)+ mx_top_offer(&top_complex, qn, name, file, cplx);+ if (cognitive > 1)+ mx_top_offer(&top_cognitive, qn, name, file, cognitive);+ if (lines > 1)+ mx_top_offer(&top_long, qn, name, file, lines);+ if (file && file[0] && file_cplx) {+ const char *canon = cbm_ht_get_key(file_cplx, file);+ if (!canon) {+ if (file_key_count >= file_key_cap) {+ int nc = file_key_cap ? file_key_cap * 2 : 1024;+ char **grown = realloc(file_keys, (size_t)nc * sizeof(char *));+ if (grown) {+ file_keys = grown;+ file_key_cap = nc;+ }+ }+ if (file_key_count < file_key_cap) {+ file_keys[file_key_count] = strdup(file);+ if (file_keys[file_key_count]) {+ canon = file_keys[file_key_count];+ file_key_count++;+ }+ }+ }+ if (canon) {+ intptr_t prev = (intptr_t)cbm_ht_get(file_cplx, canon);+ if (cplx > prev)+ cbm_ht_set(file_cplx, canon, (void *)(intptr_t)cplx);+ }+ }+ }+ sqlite3_finalize(st);+ }++ /* B. Edge certainty. */+ long long calls_edges = 0, ref_edges = 0, usage_edges = 0;+ if (sqlite3_prepare_v2(db,+ "SELECT type, COUNT(*) FROM edges WHERE project=?1 AND type IN "+ "('CALLS','CALL_REFERENCE','USAGE') GROUP BY type",+ -1, &st, NULL) == SQLITE_OK) {+ sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);+ while (sqlite3_step(st) == SQLITE_ROW) {+ const char *type = (const char *)sqlite3_column_text(st, 0);+ long long count = sqlite3_column_int64(st, 1);+ if (type && strcmp(type, "CALLS") == 0)+ calls_edges = count;+ else if (type && strcmp(type, "CALL_REFERENCE") == 0)+ ref_edges = count;+ else if (type)+ usage_edges = count;+ }+ sqlite3_finalize(st);+ }++ /* C. Dead code (candidates only; entry/test/exported excluded, matching+ * the galaxy's classifier). */+ long long dead = 0;+ if (sqlite3_prepare_v2(+ db,+ "SELECT COUNT(*) FROM nodes n WHERE n.project=?1 AND n.label IN "+ "(" CBM_SQL_CALLABLE_LABELS ") AND "+ "COALESCE(json_extract(n.properties,'$.is_entry_point'),0)=0 AND "+ "COALESCE(json_extract(n.properties,'$.is_test'),0)=0 AND "+ "COALESCE(json_extract(n.properties,'$.is_exported'),0)=0 AND "+ "NOT EXISTS (SELECT 1 FROM edges e WHERE e.project=n.project AND "+ "e.target_id=n.id AND e.type IN ('CALLS','CALL_REFERENCE','USAGE'))",+ -1, &st, NULL) == SQLITE_OK) {+ sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);+ if (sqlite3_step(st) == SQLITE_ROW)+ dead = sqlite3_column_int64(st, 0);+ sqlite3_finalize(st);+ }++ /* D. Tests + duplication. */+ long long tested = 0, similar_edges = 0;+ if (sqlite3_prepare_v2(db,+ "SELECT COUNT(DISTINCT target_id) FROM edges WHERE project=?1 AND "+ "type='TESTS'",+ -1, &st, NULL) == SQLITE_OK) {+ sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);+ if (sqlite3_step(st) == SQLITE_ROW)+ tested = sqlite3_column_int64(st, 0);+ sqlite3_finalize(st);+ }+ if (sqlite3_prepare_v2(db,+ "SELECT COUNT(*) FROM edges WHERE project=?1 AND type='SIMILAR_TO'",+ -1, &st, NULL) == SQLITE_OK) {+ sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);+ if (sqlite3_step(st) == SQLITE_ROW)+ similar_edges = sqlite3_column_int64(st, 0);+ sqlite3_finalize(st);+ }++ /* E. Missed files (coverage shadow project, #963). */+ long long missed_files = 0;+ {+ char shadow[CBM_SZ_512];+ cbm_store_coverage_shadow_project(shadow, sizeof(shadow), project);+ if (sqlite3_prepare_v2(db,+ "SELECT COUNT(*) FROM nodes WHERE project=?1 AND label='File'",+ -1, &st, NULL) == SQLITE_OK) {+ sqlite3_bind_text(st, 1, shadow, -1, SQLITE_STATIC);+ if (sqlite3_step(st) == SQLITE_ROW)+ missed_files = sqlite3_column_int64(st, 0);+ sqlite3_finalize(st);+ }+ }++ /* F. Churn (git, bounded) + churn × complexity. */+ mx_churn_t churn = {0};+ mx_churn_scan(root_path, &churn);+ mx_top_t top_churn = {0}, top_risky = {0};+ for (int i = 0; i < churn.key_count; i++) {+ const char *file = churn.keys[i];+ long long commits = (intptr_t)cbm_ht_get(churn.counts, file);+ mx_top_offer(&top_churn, NULL, NULL, file, commits);+ intptr_t max_cplx = file_cplx ? (intptr_t)cbm_ht_get(file_cplx, file) : 0;+ if (max_cplx >= MX_CHURN_MIN_CPLX)+ mx_top_offer(&top_risky, NULL, NULL, file, commits * (long long)max_cplx);+ }++ /* ── Serialize ───────────────────────────────────────────── */+ yyjson_mut_val *totals = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_int(doc, totals, "callables", callables);+ yyjson_mut_obj_add_int(doc, totals, "dead", dead);+ yyjson_mut_obj_add_int(doc, totals, "tested_symbols", tested);+ yyjson_mut_obj_add_int(doc, totals, "similar_edges", similar_edges);+ yyjson_mut_obj_add_int(doc, totals, "missed_files", missed_files);+ yyjson_mut_obj_add_int(doc, totals, "exported", exported);+ yyjson_mut_obj_add_int(doc, totals, "documented_exported", documented_exported);+ yyjson_mut_obj_add_real(doc, totals, "avg_complexity",+ callables > 0 ? (double)cplx_sum / (double)callables : 0.0);+ yyjson_mut_obj_add_val(doc, root, "totals", totals);++ yyjson_mut_val *certainty = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_int(doc, certainty, "calls", calls_edges);+ yyjson_mut_obj_add_int(doc, certainty, "call_reference", ref_edges);+ yyjson_mut_obj_add_int(doc, certainty, "usage", usage_edges);+ yyjson_mut_obj_add_val(doc, root, "certainty", certainty);++ yyjson_mut_val *cplx_arr = yyjson_mut_arr(doc);+ for (int i = 0; i < 6; i++)+ yyjson_mut_arr_add_int(doc, cplx_arr, cplx_hist[i]);+ yyjson_mut_obj_add_val(doc, root, "complexity_hist", cplx_arr);+ yyjson_mut_val *line_arr = yyjson_mut_arr(doc);+ for (int i = 0; i < 5; i++)+ yyjson_mut_arr_add_int(doc, line_arr, line_hist[i]);+ yyjson_mut_obj_add_val(doc, root, "lines_hist", line_arr);++ mx_top_json(doc, root, "top_complex", &top_complex);+ mx_top_json(doc, root, "top_cognitive", &top_cognitive);+ mx_top_json(doc, root, "top_long", &top_long);+ mx_top_json(doc, root, "top_churn", &top_churn);+ mx_top_json(doc, root, "top_churn_complex", &top_risky);+ yyjson_mut_obj_add_bool(doc, root, "churn_available", churn.counts != NULL);++ long long callish = calls_edges + ref_edges + usage_edges;+ mx_history_append_and_emit(doc, root, project, stamp, callables, dead,+ callables > 0 ? (double)cplx_sum / (double)callables : 0.0,+ tested, usage_edges, callish);++ mx_top_free(&top_complex);+ mx_top_free(&top_cognitive);+ mx_top_free(&top_long);+ mx_top_free(&top_churn);+ mx_top_free(&top_risky);+ mx_churn_free(&churn);+ cbm_ht_free(file_cplx);+ for (int i = 0; i < file_key_count; i++)+ free(file_keys[i]);+ free(file_keys);++ char *json = yyjson_mut_write(doc, 0, NULL);+ yyjson_mut_doc_free(doc);+ return json;+}++char *cbm_atlas_metrics_json(cbm_store_t *store, const char *project) {+ if (!store || !project)+ return NULL;+ char stamp[128];+ char root_path[CBM_SZ_1K];+ mx_project_stamp(store, project, stamp, sizeof(stamp), root_path, sizeof(root_path));+ char key[1280];+ snprintf(key, sizeof(key), "%s|%s", project, stamp);+ pthread_mutex_lock(&g_mx_mu);+ if (g_mx_cache.json && strcmp(g_mx_cache.key, key) == 0) {+ char *copy = strdup(g_mx_cache.json);+ pthread_mutex_unlock(&g_mx_mu);+ return copy;+ }+ pthread_mutex_unlock(&g_mx_mu);++ char *json = mx_build_json(store, project, stamp, root_path);+ if (!json)+ return NULL;+ pthread_mutex_lock(&g_mx_mu);+ free(g_mx_cache.json);+ g_mx_cache.json = strdup(json);+ snprintf(g_mx_cache.key, sizeof(g_mx_cache.key), "%s", key);+ pthread_mutex_unlock(&g_mx_mu);+ return json;+}diff --git a/src/ui/http_server.c b/src/ui/http_server.cindex 428d73dff..ed02d649d 100644--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@ -1818,6 +1818,17 @@ static void handle_atlas_symbol(cbm_http_conn_t *c, const cbm_http_req_t *req) {atlas_reply_json(c, json, 404, "{\"error\":\"symbol not found\"}");}+/* GET /api/metrics?project=X — the Dashboard payload. */+static void handle_atlas_metrics(cbm_http_conn_t *c, const cbm_http_req_t *req) {+ char project[256] = {0};+ cbm_store_t *store = atlas_open_project(c, req, project, sizeof(project));+ if (!store)+ return;+ char *json = cbm_atlas_metrics_json(store, project);+ cbm_store_close(store);+ atlas_reply_json(c, json, 500, "{\"error\":\"metrics computation failed\"}");+}+/* GET /api/flows?project=X — ranked entry→terminal flows. */static void handle_atlas_flows(cbm_http_conn_t *c, const cbm_http_req_t *req) {char project[256] = {0};@@ -2131,6 +2142,12 @@ static void dispatch_request(cbm_http_server_t *srv, cbm_http_conn_t *c,return;}+ /* GET /api/metrics → CBM Atlas dashboard payload */+ if (is_get && cbm_http_path_match(req->path, "/api/metrics*")) {+ handle_atlas_metrics(c, req);+ return;+ }+/* GET /api/flows → CBM Atlas flow list */if (is_get && cbm_http_path_match(req->path, "/api/flows*")) {handle_atlas_flows(c, req);diff --git a/tests/test_httpd.c b/tests/test_httpd.cindex f1df83347..8064fea72 100644--- a/tests/test_httpd.c+++ b/tests/test_httpd.c@@ -1191,7 +1191,8 @@ TEST(ui_server_atlas_routes_are_wired) {* falls through to the static handler's 404. This pins the /api/flow* (singular) route, which once used a "?*" pattern that never matched* because req->path carries no query string. */- static const char *const routes[] = {"/api/tree", "/api/symbol", "/api/flows", "/api/flow"};+ static const char *const routes[] = {"/api/tree", "/api/symbol", "/api/flows", "/api/flow",+ "/api/metrics"};char req[256];char resp[4096];for (size_t i = 0; i < sizeof(routes) / sizeof(routes[0]); i++) {diff --git a/tests/test_ui.c b/tests/test_ui.cindex 2d60424c5..0f402294f 100644--- a/tests/test_ui.c+++ b/tests/test_ui.c@@ -1300,6 +1300,51 @@ TEST(atlas_flows_walk_and_rank) {PASS();}+TEST(atlas_metrics_totals_and_certainty) {+ cbm_layout_regions_cache_clear();+ cbm_atlas_metrics_cache_clear();+ cbm_store_t *store = atlas_fixture(NULL);+ ASSERT_NOT_NULL(store);++ char *json = cbm_atlas_metrics_json(store, "regions-test");+ ASSERT_NOT_NULL(json);+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *root = yyjson_doc_get_root(doc);++ yyjson_val *totals = yyjson_obj_get(root, "totals");+ /* 6 fixture functions + test_alpha_one. */+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(totals, "callables")), 7);+ /* test_alpha_one has no callers but is in a test path — flags absent, so+ * it counts as dead alongside beta callables the cycle keeps alive;+ * alpha_one is entry-flagged and beta_* all have inbound CALLS: only the+ * test function has zero inbound call-ish edges. */+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(totals, "dead")), 1);+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(totals, "tested_symbols")), 1);+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(totals, "similar_edges")), 1);+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(totals, "missed_files")), 1);++ yyjson_val *certainty = yyjson_obj_get(root, "certainty");+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(certainty, "calls")), 9);++ /* Histograms cover every callable exactly once. */+ yyjson_val *hist = yyjson_obj_get(root, "complexity_hist");+ long long sum = 0;+ size_t idx, max;+ yyjson_val *bucket;+ yyjson_arr_foreach(hist, idx, max, bucket) sum += yyjson_get_int(bucket);+ ASSERT_EQ((int)sum, 7);++ ASSERT_NOT_NULL(yyjson_obj_get(root, "history"));++ yyjson_doc_free(doc);+ free(json);+ cbm_store_close(store);+ cbm_atlas_metrics_cache_clear();+ cbm_layout_regions_cache_clear();+ PASS();+}+/* ── Suite ────────────────────────────────────────────────────── */SUITE(ui) {@@ -1336,4 +1381,5 @@ SUITE(ui) {RUN_TEST(atlas_tree_aggregates_children);RUN_TEST(atlas_symbol_bundle_totals_and_sections);RUN_TEST(atlas_flows_walk_and_rank);+ RUN_TEST(atlas_metrics_totals_and_certainty);}