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(atlas): galaxy orientation — search scent, minimap, region cards
Martin Vogel03995b746131
diff --git a/graph-ui/src/components/GraphScene.tsx b/graph-ui/src/components/GraphScene.tsxindex 9a1ce2f6b..f6b8ec1e0 100644--- a/graph-ui/src/components/GraphScene.tsx+++ b/graph-ui/src/components/GraphScene.tsx@@ -124,6 +124,8 @@ interface GraphSceneProps {/* Fired when a click hits empty space (no node). Used to fly back to the* overview after focusing the missed skeleton. */onBackgroundClick?: () => void;+ /* Custom hover card (the region scene shows region facts, not node ones). */+ renderTooltip?: (node: GraphNode) => React.ReactNode;}export type { CameraTarget };@@ -137,6 +139,7 @@ export function GraphScene({display = DEFAULT_DISPLAY_SETTINGS,onNodeClick,onBackgroundClick,+ renderTooltip,}: GraphSceneProps) {const [hovered, setHovered] = useState<GraphNode | null>(null);const controlsRef = useRef<OrbitControlsImpl | null>(null);@@ -251,7 +254,8 @@ export function GraphScene({);})}- {hovered && <NodeTooltip node={hovered} />}+ {hovered &&+ (renderTooltip ? renderTooltip(hovered) : <NodeTooltip node={hovered} />)}<CameraAnimator target={cameraTarget} controlsRef={controlsRef} /><IdleAutoRotate controlsRef={controlsRef} />diff --git a/graph-ui/src/components/GraphTab.regions.test.tsx b/graph-ui/src/components/GraphTab.regions.test.tsxindex ae21bb108..6a77b8186 100644--- a/graph-ui/src/components/GraphTab.regions.test.tsx+++ b/graph-ui/src/components/GraphTab.regions.test.tsx@@ -92,8 +92,12 @@ describe("GraphTab region level", () => {render(<GraphTab project="demo" />);/* The region list is the left panel; both regions are listed. */- expect(await screen.findByText("src/alpha")).toBeInTheDocument();- expect(screen.getByText("src/beta")).toBeInTheDocument();+ expect(+ (await screen.findAllByText("src/alpha")).some((el) => el.tagName === "SPAN"),+ ).toBe(true);+ expect(+ screen.getAllByText("src/beta").some((el) => el.tagName === "SPAN"),+ ).toBe(true);expect(screen.getByRole("button", { name: "Load full galaxy" })).toBeInTheDocument();/* No full layout was fetched — only the region probe. */@@ -106,7 +110,9 @@ describe("GraphTab region level", () => {const fetchMock = mockAtlasFetch();render(<GraphTab project="demo" />);- fireEvent.click(await screen.findByText("src/alpha"));+ fireEvent.click(+ (await screen.findAllByText("src/alpha")).find((el) => el.tagName === "SPAN")!,+ );/* The region panel shows provenance and the door in. */expect(screen.getByText("call community: 2 files, 100% under src/alpha"),@@ -139,7 +145,9 @@ describe("GraphTab region level", () => {expect(await screen.findByText("region: src/alpha")).toBeInTheDocument();/* Select the only node via the sidebar symbol row (#1197). */- fireEvent.click(screen.getByText("src/alpha")); /* expand the tree */+ fireEvent.click(+ screen.getAllByText("src/alpha").find((el) => el.tagName === "SPAN")!,+ ); /* expand the tree */fireEvent.click(await screen.findByText("alpha_one"));expect(onRouteChange).toHaveBeenCalledWith("7", "0");/* The detail panel now shows the node, not a stale or empty panel. */diff --git a/graph-ui/src/components/GraphTab.tsx b/graph-ui/src/components/GraphTab.tsxindex a29f001e0..7cd10d40a 100644--- a/graph-ui/src/components/GraphTab.tsx+++ b/graph-ui/src/components/GraphTab.tsx@@ -9,6 +9,10 @@ import {GRAPH_NODE_BUDGET_MAX,} from "../hooks/useGraphData";import { regionsToGraphData, regionsViewWorthwhile, disambiguateRegionNames, isTestRegion } from "../lib/regions";+import { fetchScent } from "../lib/atlas";+import { RegionTooltip } from "./RegionTooltip";+import { NodeTooltip } from "./NodeTooltip";+import { Minimap } from "./Minimap";import { RegionPanel } from "./RegionPanel";import { GraphLoader } from "./GraphLoader";import { DisplaySettingsMenu } from "./DisplaySettingsMenu";@@ -334,6 +338,44 @@ export function GraphTab({};}, [project]);+ /* Search scent: a query is answerable from the coarsest view — matched+ * regions brighten and carry hit counts before any drill. */+ const [scentQuery, setScentQuery] = useState("");+ const [scent, setScent] = useState<{+ total: number;+ unmapped: number;+ counts: Map<number, number>;+ } | null>(null);+ useEffect(() => {+ setScentQuery("");+ setScent(null);+ }, [project]);+ useEffect(() => {+ const q = scentQuery.trim();+ if (!project || q.length < 2) {+ setScent(null);+ return;+ }+ let cancelled = false;+ const timer = setTimeout(async () => {+ try {+ const payload = await fetchScent(project, q);+ if (cancelled) return;+ setScent({+ total: payload.total,+ unmapped: payload.unmapped,+ counts: new Map(payload.regions.map((row) => [row.region, row.count])),+ });+ } catch {+ if (!cancelled) setScent(null);+ }+ }, 300);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [project, scentQuery]);+const handleSelectPath = useCallback((path: string, nodeIds: Set<number>) => {if (!filteredData || !path || nodeIds.size === 0) {@@ -506,6 +548,20 @@ export function GraphTab({? "call communities + folder groups": "folder groups"}</p>+ <input+ type="text"+ value={scentQuery}+ onChange={(e) => setScentQuery(e.target.value)}+ placeholder="find a symbol…"+ className="mt-2 w-full bg-popover border border-border/50 rounded-md px-2 py-1 text-[13px] text-foreground placeholder-foreground/30 outline-none focus:border-primary/50 transition-all"+ />+ {scent && (+ <p className="text-[12px] text-primary/70 mt-1 tabular-nums">+ {scent.total.toLocaleString("en-US")} match+ {scent.total === 1 ? "" : "es"}+ {scent.unmapped > 0 && ` · ${scent.unmapped} outside regions`}+ </p>+ )}</div><div className="flex-1 min-h-0 overflow-y-auto py-1">{[...displayRegions]@@ -526,6 +582,11 @@ export function GraphTab({style={{ backgroundColor: region.color }}/><span className="truncate">{region.name}</span>+ {(scent?.counts.get(region.id) ?? 0) > 0 && (+ <span className="text-primary text-[11px] tabular-nums shrink-0 bg-primary/15 rounded-full px-1.5">+ {scent?.counts.get(region.id)}+ </span>+ )}<span className="text-foreground/30 ml-auto text-[12px] tabular-nums shrink-0">{region.members.toLocaleString("en-US")}</span>@@ -549,7 +610,13 @@ export function GraphTab({<GraphScenedata={regionGraph}missed={null}- highlightedIds={selected ? new Set([selected.id]) : null}+ highlightedIds={+ scent && scent.counts.size > 0+ ? new Set(scent.counts.keys())+ : selected+ ? new Set([selected.id])+ : null+ }cameraTarget={cameraTarget}showLabels={true}display={display}@@ -563,9 +630,32 @@ export function GraphTab({}}}onBackgroundClick={() => setSelectedRegion(null)}+ renderTooltip={(node) => {+ const region = displayRegions.find((r) => r.id === node.id);+ return region ? (+ <RegionTooltip region={region} node={node} />+ ) : (+ <NodeTooltip node={node} />+ );+ }}/></ErrorBoundary>+ <Minimap+ regions={displayRegions}+ openRegionId={null}+ scentCounts={scent?.counts ?? null}+ onOpen={openRegion}+ onHome={() =>+ setCameraTarget(+ computeCameraTarget(+ regionGraph.nodes,+ new Set(regionGraph.nodes.map((n) => n.id)),+ ),+ )+ }+ />+<div className="absolute top-4 left-4 text-[13px] text-foreground/55 pointer-events-none tabular-nums"><p>{displayRegions.length} regions /{" "}@@ -717,6 +807,21 @@ export function GraphTab({/></ErrorBoundary>+ <Minimap+ regions={displayRegions}+ openRegionId={view.kind === "region" ? view.region.id : null}+ scentCounts={null}+ onOpen={openRegion}+ onHome={() =>+ setCameraTarget(+ computeCameraTarget(+ filteredData.nodes,+ new Set(filteredData.nodes.map((n) => n.id)),+ ),+ )+ }+ />+{/* HUD */}<div className="absolute top-4 left-4 text-[13px] text-foreground/55 pointer-events-none tabular-nums">{regionsError && (@@ -850,6 +955,17 @@ export function GraphTab({allEdges={filteredData.edges}project={project}repoInfo={repoInfo}+ scopeNote={(() => {+ if (view.kind !== "region" || selectedNode.in_calls === undefined)+ return null;+ const visible = filteredData.edges.filter(+ (e) => e.target === selectedNode.id && e.type === "CALLS",+ ).length;+ const outside = selectedNode.in_calls - visible;+ return outside > 0+ ? `+${outside.toLocaleString("en-US")} caller${outside === 1 ? "" : "s"} outside this region`+ : null;+ })()}onClose={() => {setSelectedNode(null);setHighlightedIds(null);diff --git a/graph-ui/src/components/Minimap.tsx b/graph-ui/src/components/Minimap.tsxnew file mode 100644index 000000000..9e5b87f9b--- /dev/null+++ b/graph-ui/src/components/Minimap.tsx@@ -0,0 +1,149 @@+import { useMemo, useState } from "react";+import type { Region } from "../lib/types";++/* The 2D synced panel of the orientation triad: every region as a colored+ * dot on a fixed top-down projection, so the 3D view always has a stable+ * "you are here" companion. Click a dot to open that region. */++export interface MinimapDot {+ id: number;+ cx: number;+ cy: number;+ r: number;+ color: string;+ name: string;+}++export function minimapLayout(+ regions: Region[],+ width: number,+ height: number,+ pad = 12,+): MinimapDot[] {+ if (regions.length === 0) return [];+ let minX = Infinity,+ maxX = -Infinity,+ minY = Infinity,+ maxY = -Infinity;+ for (const region of regions) {+ minX = Math.min(minX, region.x);+ maxX = Math.max(maxX, region.x);+ minY = Math.min(minY, region.y);+ maxY = Math.max(maxY, region.y);+ }+ const spanX = maxX - minX || 1;+ const spanY = maxY - minY || 1;+ const maxMembers = Math.max(...regions.map((region) => region.members), 1);+ return regions.map((region) => ({+ id: region.id,+ cx: pad + ((region.x - minX) / spanX) * (width - pad * 2),+ cy: pad + ((region.y - minY) / spanY) * (height - pad * 2),+ r: 3 + 7 * Math.sqrt(region.members / maxMembers),+ color: region.color,+ name: region.name,+ }));+}++const W = 190;+const H = 150;++export function Minimap({+ regions,+ openRegionId,+ scentCounts,+ onOpen,+ onHome,+}: {+ regions: Region[];+ openRegionId: number | null;+ scentCounts: Map<number, number> | null;+ onOpen: (region: Region) => void;+ onHome: () => void;+}) {+ const [collapsed, setCollapsed] = useState(() => {+ try {+ return localStorage.getItem("cbm-minimap-collapsed") === "1";+ } catch {+ return false;+ }+ });+ const dots = useMemo(() => minimapLayout(regions, W, H), [regions]);+ const byId = useMemo(() => new Map(regions.map((r) => [r.id, r])), [regions]);++ const toggle = () => {+ setCollapsed((v) => {+ try {+ localStorage.setItem("cbm-minimap-collapsed", v ? "0" : "1");+ } catch {+ /* ignore */+ }+ return !v;+ });+ };++ if (regions.length === 0) return null;+ return (+ <div className="absolute bottom-4 right-4 bg-card/85 backdrop-blur border border-border/50 rounded-md shadow-lg overflow-hidden">+ <div className="flex items-center gap-1 px-2 py-1 border-b border-border/30">+ <span className="text-[12px] uppercase tracking-widest text-foreground/40">+ map+ </span>+ <button+ onClick={onHome}+ title="Fit everything in view"+ className="ml-auto text-foreground/45 hover:text-foreground/80 text-[13px] leading-none px-1 transition-colors"+ >+ ⌂+ </button>+ <button+ onClick={toggle}+ title={collapsed ? "Expand map" : "Collapse map"}+ className="text-foreground/45 hover:text-foreground/80 text-[13px] leading-none px-1 transition-colors"+ >+ {collapsed ? "▴" : "▾"}+ </button>+ </div>+ {!collapsed && (+ <svg width={W} height={H} role="img" aria-label="Region minimap">+ {dots.map((dot) => {+ const isOpen = dot.id === openRegionId;+ const hits = scentCounts?.get(dot.id) ?? 0;+ return (+ <g+ key={dot.id}+ onClick={() => {+ const region = byId.get(dot.id);+ if (region) onOpen(region);+ }}+ className="cursor-pointer"+ >+ <title>{dot.name}</title>+ <circle+ cx={dot.cx}+ cy={dot.cy}+ r={dot.r}+ fill={dot.color}+ fillOpacity={scentCounts && hits === 0 ? 0.25 : 0.85}+ stroke={isOpen ? "#4FA8E0" : "none"}+ strokeWidth={isOpen ? 2 : 0}+ />+ {hits > 0 && (+ <text+ x={dot.cx}+ y={dot.cy - dot.r - 2}+ textAnchor="middle"+ fontSize="9"+ fill="#4FA8E0"+ className="tabular-nums"+ >+ {hits}+ </text>+ )}+ </g>+ );+ })}+ </svg>+ )}+ </div>+ );+}diff --git a/graph-ui/src/components/NodeDetailPanel.tsx b/graph-ui/src/components/NodeDetailPanel.tsxindex 90351b8f6..69a6141e2 100644--- a/graph-ui/src/components/NodeDetailPanel.tsx+++ b/graph-ui/src/components/NodeDetailPanel.tsx@@ -21,6 +21,9 @@ interface NodeDetailPanelProps {repoInfo: RepoInfo | null;onClose: () => void;onNavigate: (node: GraphNode) => void;+ /* Honest-scope note, e.g. "+12 callers outside this region" — the loaded+ * edges are a window, never the whole truth. */+ scopeNote?: string | null;}interface SnippetResult {@@ -56,6 +59,7 @@ export function NodeDetailPanel({repoInfo,onClose,onNavigate,+ scopeNote = null,}: NodeDetailPanelProps) {const [code, setCode] = useState<string | null>(null);const [codeLoading, setCodeLoading] = useState(false);@@ -197,6 +201,9 @@ export function NodeDetailPanel({{outbound.length > 0 && (<ConnectionSection title="References" count={outbound.length} icon="→" groups={groupByType(outbound)} onNavigate={onNavigate} />)}+ {scopeNote && (+ <p className="text-[12px] text-warn/80">{scopeNote}</p>+ )}{inbound.length > 0 && (<ConnectionSection title="Referenced by" count={inbound.length} icon="←" groups={groupByType(inbound)} onNavigate={onNavigate} />)}diff --git a/graph-ui/src/components/NodeTooltip.tsx b/graph-ui/src/components/NodeTooltip.tsxindex a9bdb45db..185983e09 100644--- a/graph-ui/src/components/NodeTooltip.tsx+++ b/graph-ui/src/components/NodeTooltip.tsx@@ -20,7 +20,7 @@ export function NodeTooltip({ node }: NodeTooltipProps) {centerstyle={{ pointerEvents: "none" }}>- <div className="bg-[#1a1a2e]/95 backdrop-blur border border-white/10 rounded-md px-3 py-2 text-xs whitespace-nowrap shadow-xl max-w-[350px]">+ <div className="bg-popover/95 backdrop-blur border border-border/60 rounded-md px-3 py-2 text-xs whitespace-nowrap shadow-xl max-w-[350px]"><div className="flex items-center gap-1.5 mb-1"><spanclassName="w-2 h-2 rounded-full shrink-0"@@ -43,8 +43,9 @@ export function NodeTooltip({ node }: NodeTooltipProps) {/><span className="text-foreground/45">{node.status}</span>{node.in_calls !== undefined && (- <span className="text-foreground/40">- · {node.in_calls} caller{node.in_calls === 1 ? "" : "s"}+ <span className="text-foreground/40 tabular-nums">+ · in {node.in_calls}+ {node.out_calls !== undefined && ` · out ${node.out_calls}`}</span>)}</div>diff --git a/graph-ui/src/components/RegionTooltip.tsx b/graph-ui/src/components/RegionTooltip.tsxnew file mode 100644index 000000000..ff6577d81--- /dev/null+++ b/graph-ui/src/components/RegionTooltip.tsx@@ -0,0 +1,34 @@+import { Html } from "@react-three/drei";+import type { GraphNode, Region } from "../lib/types";+import { cohesionWord } from "../lib/regions";++/* Hover card for a region blob in the coarsest galaxy view: what a human+ * needs before deciding to drill — size, cohesion in words, the hub. */+export function RegionTooltip({ region, node }: { region: Region; node: GraphNode }) {+ return (+ <Html+ position={[node.x, node.y + node.size * 0.7, node.z]}+ center+ style={{ pointerEvents: "none" }}+ >+ <div className="bg-popover/95 backdrop-blur border border-border/60 rounded-md px-3 py-2 text-xs whitespace-nowrap shadow-xl max-w-[360px]">+ <div className="flex items-center gap-1.5 mb-1">+ <span+ className="w-2 h-2 rounded-full shrink-0"+ style={{ backgroundColor: region.color }}+ />+ <span className="text-foreground font-medium truncate">{region.name}</span>+ </div>+ <p className="text-foreground/50 tabular-nums">+ {region.members.toLocaleString("en-US")} symbols ·{" "}+ {region.files.toLocaleString("en-US")} files ·{" "}+ {cohesionWord(region.cohesion)} ({region.cohesion.toFixed(2)})+ </p>+ {region.hub && (+ <p className="text-foreground/45 font-mono truncate mt-0.5">hub: {region.hub}</p>+ )}+ <p className="text-foreground/35 mt-1 text-[12px]">double-click to open →</p>+ </div>+ </Html>+ );+}diff --git a/graph-ui/src/lib/atlas.ts b/graph-ui/src/lib/atlas.tsindex efa3e546c..32b9a0880 100644--- a/graph-ui/src/lib/atlas.ts+++ b/graph-ui/src/lib/atlas.ts@@ -277,3 +277,18 @@ export function fetchTrace(const params = new URLSearchParams({ project, from, to, mode });return getJson(`/api/trace?${params}`);}++/* ── /api/scent — per-region search hit counts ─────────────────── */++export interface ScentPayload {+ query: string;+ total: number;+ unmapped: number;+ capped: boolean;+ regions: { region: number; count: number }[];+}++export function fetchScent(project: string, q: string): Promise<ScentPayload> {+ const params = new URLSearchParams({ project, q });+ return getJson(`/api/scent?${params}`);+}diff --git a/graph-ui/src/lib/regions.test.ts b/graph-ui/src/lib/regions.test.tsindex 7c6b3a834..b4233b507 100644--- a/graph-ui/src/lib/regions.test.ts+++ b/graph-ui/src/lib/regions.test.ts@@ -4,7 +4,9 @@ import {regionsToGraphData,regionsViewWorthwhile,REGIONS_MIN_TOTAL_NODES,+ cohesionWord,} from "./regions";+import { minimapLayout } from "../components/Minimap";import type { Region, RegionsPayload } from "./types";function region(partial: Partial<Region> & { id: number; name: string }): Region {@@ -66,3 +68,46 @@ describe("region adapters", () => {).toBe(false);});});++describe("cohesionWord", () => {+ it("maps scores to the 0.7/0.4 word ladder", () => {+ expect(cohesionWord(0.84)).toBe("tightly connected");+ expect(cohesionWord(0.62)).toBe("moderately connected");+ expect(cohesionWord(0.11)).toBe("loosely connected");+ });+});++describe("minimapLayout", () => {+ const region = (id: number, x: number, y: number, members: number): Region => ({+ id,+ name: `r${id}`,+ files: 1,+ members,+ cohesion: 0.5,+ top_nodes: [],+ x,+ y,+ z: 0,+ size: 10,+ color: "#123456",+ });+ it("projects region positions into the padded viewport", () => {+ const dots = minimapLayout([region(0, -100, 0, 100), region(1, 100, 50, 25)], 200, 150);+ expect(dots).toHaveLength(2);+ expect(dots[0].cx).toBe(12);+ expect(dots[1].cx).toBe(188);+ expect(dots[0].cy).toBe(12);+ expect(dots[1].cy).toBe(138);+ /* Biggest region gets the biggest dot; both stay in bounds. */+ expect(dots[0].r).toBeGreaterThan(dots[1].r);+ for (const dot of dots) {+ expect(dot.cx).toBeGreaterThanOrEqual(0);+ expect(dot.cx).toBeLessThanOrEqual(200);+ }+ });+ it("handles a single region without dividing by zero", () => {+ const dots = minimapLayout([region(7, 42, 42, 10)], 200, 150);+ expect(dots).toHaveLength(1);+ expect(Number.isFinite(dots[0].cx)).toBe(true);+ });+});diff --git a/graph-ui/src/lib/regions.ts b/graph-ui/src/lib/regions.tsindex 704bd60fa..faa2557db 100644--- a/graph-ui/src/lib/regions.ts+++ b/graph-ui/src/lib/regions.ts@@ -85,3 +85,11 @@ export function lensRegionsPayload(export function isBuiltinQn(qn: string): boolean {return /(^|\.)builtins?\./.test(qn) || /(^|\.)__builtins__\./.test(qn);}++/* Score → word: numbers alone don't teach. Thresholds match the+ * moderately-connected convention (0.7 / 0.4). */+export function cohesionWord(cohesion: number): string {+ if (cohesion >= 0.7) return "tightly connected";+ if (cohesion >= 0.4) return "moderately connected";+ return "loosely connected";+}diff --git a/graph-ui/src/lib/types.ts b/graph-ui/src/lib/types.tsindex c3c74743b..76bd67b02 100644--- a/graph-ui/src/lib/types.ts+++ b/graph-ui/src/lib/types.ts@@ -16,6 +16,7 @@ export interface GraphNode {/* Dead-code classification from the backend layout (layout3d.c). */status?: NodeStatus;in_calls?: number;+ out_calls?: number;}export type NodeStatus =diff --git a/src/ui/atlas.h b/src/ui/atlas.hindex ab94d639e..125895c0e 100644--- a/src/ui/atlas.h+++ b/src/ui/atlas.h@@ -55,6 +55,8 @@ char *cbm_atlas_file_history_json(cbm_store_t *store, const char *project, const* Reachability between two callables over CALLS ("calls") or DATA_FLOWS* ("data"): shortest path within a bounded depth, honest about the bound.* Endpoints resolve by node id (>=0) or qualified name. */+char *cbm_atlas_scent_json(cbm_store_t *store, const char *project, const char *query);+char *cbm_atlas_trace_json(cbm_store_t *store, const char *project, int64_t from_id,const char *from_qn, int64_t to_id, const char *to_qn, const char *mode);diff --git a/src/ui/atlas_api.c b/src/ui/atlas_api.cindex 6a82278d4..be41fda8a 100644--- a/src/ui/atlas_api.c+++ b/src/ui/atlas_api.c@@ -595,3 +595,86 @@ char *cbm_atlas_symbol_json(cbm_store_t *store, const char *project, int64_t nodyyjson_mut_doc_free(doc);return json;}++/* ── Scent: per-region hit counts for a symbol-name search ────────+ * The search-scent idea: a query should be answerable from the coarsest+ * view, so region blobs and list rows carry match counts before any drill.+ * Case-insensitive substring match on node name, bucketed by region via the+ * cached file->region map. */++char *cbm_atlas_scent_json(cbm_store_t *store, const char *project, const char *query) {+ if (!store || !project || !query || strlen(query) < 2)+ return NULL;+ struct sqlite3 *db = cbm_store_get_db(store);+ if (!db)+ return NULL;++ enum { SCENT_MAX_MATCHES = 50000, SCENT_MAX_REGIONS = 4096 };+ long long *counts = calloc(SCENT_MAX_REGIONS, sizeof(long long));+ if (!counts)+ return NULL;+ long long total = 0, unmapped = 0;+ bool capped = false;++ /* Escape LIKE wildcards so a literal "_" in the query stays literal. */+ char pattern[512];+ {+ size_t w = 0;+ pattern[w++] = '%';+ for (const char *c = query; *c && w < sizeof(pattern) - 3; c++) {+ if (*c == '%' || *c == '_' || *c == '\\')+ pattern[w++] = '\\';+ pattern[w++] = *c;+ }+ pattern[w++] = '%';+ pattern[w] = '\0';+ }++ sqlite3_stmt *st = NULL;+ if (sqlite3_prepare_v2(db,+ "SELECT file_path FROM nodes WHERE project=?1 AND name LIKE ?2 "+ "ESCAPE '\\' COLLATE NOCASE AND file_path IS NOT NULL "+ "AND label NOT IN ('File','Folder')",+ -1, &st, NULL) != SQLITE_OK) {+ free(counts);+ return NULL;+ }+ sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);+ sqlite3_bind_text(st, 2, pattern, -1, SQLITE_STATIC);+ while (sqlite3_step(st) == SQLITE_ROW) {+ if (total >= SCENT_MAX_MATCHES) {+ capped = true;+ break;+ }+ const char *fp = (const char *)sqlite3_column_text(st, 0);+ total++;+ int region = fp ? cbm_layout_region_for_file(store, project, fp, NULL) : -1;+ if (region >= 0 && region < SCENT_MAX_REGIONS)+ counts[region]++;+ else+ unmapped++;+ }+ sqlite3_finalize(st);++ 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, "query", query);+ yyjson_mut_obj_add_int(doc, root, "total", total);+ yyjson_mut_obj_add_int(doc, root, "unmapped", unmapped);+ yyjson_mut_obj_add_bool(doc, root, "capped", capped);+ yyjson_mut_val *arr = yyjson_mut_arr(doc);+ for (int i = 0; i < SCENT_MAX_REGIONS; i++) {+ if (counts[i] == 0)+ continue;+ yyjson_mut_val *row = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_int(doc, row, "region", i);+ yyjson_mut_obj_add_int(doc, row, "count", counts[i]);+ yyjson_mut_arr_append(arr, row);+ }+ yyjson_mut_obj_add_val(doc, root, "regions", arr);+ free(counts);+ char *json = yyjson_mut_write(doc, 0, NULL);+ yyjson_mut_doc_free(doc);+ return json;+}diff --git a/src/ui/http_server.c b/src/ui/http_server.cindex 0aae4d82d..16ed7c7de 100644--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@ -1848,6 +1848,24 @@ static void handle_atlas_trace(cbm_http_conn_t *c, const cbm_http_req_t *req) {atlas_reply_json(c, json, 500, "{\"error\":\"trace failed\"}");}+/* GET /api/scent?project=X&q=pattern — per-region search hit counts. */+static void handle_atlas_scent(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 q[256] = {0};+ cbm_http_query_param(req->query, "q", q, (int)sizeof(q));+ if (strlen(q) < 2) {+ cbm_store_close(store);+ cbm_http_replyf(c, 400, g_cors_json, "{\"error\":\"q must be at least 2 characters\"}");+ return;+ }+ char *json = cbm_atlas_scent_json(store, project, q);+ cbm_store_close(store);+ atlas_reply_json(c, json, 500, "{\"error\":\"scent 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};@@ -2167,6 +2185,12 @@ static void dispatch_request(cbm_http_server_t *srv, cbm_http_conn_t *c,return;}+ /* GET /api/scent → CBM Atlas per-region search counts */+ if (is_get && cbm_http_path_match(req->path, "/api/scent*")) {+ handle_atlas_scent(c, req);+ return;+ }+/* GET /api/trace → CBM Atlas A→B reachability */if (is_get && cbm_http_path_match(req->path, "/api/trace*")) {handle_atlas_trace(c, req);diff --git a/src/ui/layout3d.c b/src/ui/layout3d.cindex f7802d3f5..6a980d8d2 100644--- a/src/ui/layout3d.c+++ b/src/ui/layout3d.c@@ -667,17 +667,19 @@ cbm_layout_result_t *cbm_layout_from_nodes(cbm_store_t *store, const char *proje* having zero callers. */int64_t *node_ids = malloc((size_t)n * sizeof(int64_t));int *in_calls = calloc((size_t)n, sizeof(int));+ int *out_calls = calloc((size_t)n, sizeof(int));int *in_usage = calloc((size_t)n, sizeof(int));int *in_call_reference = calloc((size_t)n, sizeof(int));int *deg_dummy = calloc((size_t)n, sizeof(int));- bool dead_degrees_valid = node_ids && in_calls && in_usage && in_call_reference && deg_dummy;+ bool dead_degrees_valid =+ node_ids && in_calls && out_calls && in_usage && in_call_reference && deg_dummy;if (dead_degrees_valid) {for (int i = 0; i < n; i++)node_ids[i] = nodes[i].id;for (int off = 0; off < n; off += DEAD_DEGREE_CHUNK) {int cnt = (n - off < DEAD_DEGREE_CHUNK) ? (n - off) : DEAD_DEGREE_CHUNK;if (cbm_store_batch_count_degrees(store, node_ids + off, cnt, "CALLS", in_calls + off,- deg_dummy + off) != CBM_STORE_OK ||+ out_calls + off) != CBM_STORE_OK ||cbm_store_batch_count_degrees(store, node_ids + off, cnt, "USAGE", in_usage + off,deg_dummy + off) != CBM_STORE_OK ||cbm_store_batch_count_degrees(store, node_ids + off, cnt, "CALL_REFERENCE",@@ -764,6 +766,7 @@ cbm_layout_result_t *cbm_layout_from_nodes(cbm_store_t *store, const char *projeelsestatus = "normal";result->nodes[i].in_calls = ic;+ result->nodes[i].out_calls = dead_degrees_valid ? out_calls[i] : 0;result->nodes[i].status = status;}@@ -795,6 +798,7 @@ cbm_layout_result_t *cbm_layout_from_nodes(cbm_store_t *store, const char *projefree(cdepth);free(node_ids);free(in_calls);+ free(out_calls);free(in_usage);free(in_call_reference);free(deg_dummy);@@ -853,6 +857,7 @@ char *cbm_layout_to_json(const cbm_layout_result_t *r) {snprintf(hex, sizeof(hex), "#%06x", r->nodes[i].color);yyjson_mut_obj_add_strcpy(doc, nd, "color", hex);yyjson_mut_obj_add_int(doc, nd, "in_calls", r->nodes[i].in_calls);+ yyjson_mut_obj_add_int(doc, nd, "out_calls", r->nodes[i].out_calls);if (r->nodes[i].status)yyjson_mut_obj_add_str(doc, nd, "status", r->nodes[i].status);yyjson_mut_arr_append(na, nd);diff --git a/src/ui/layout3d.h b/src/ui/layout3d.hindex fc1e9ebaa..44d71aa0c 100644--- a/src/ui/layout3d.h+++ b/src/ui/layout3d.h@@ -27,6 +27,7 @@ typedef struct {float size; /* visual size */uint32_t color; /* 0xRRGGBB */int in_calls; /* incoming CALLS-family degree (full graph, not sampled) */+ int out_calls; /* outgoing CALLS degree (full graph) *//* Dead-code classification (string literal, NOT freed):* "dead"|"single"|"entry"|"test"|"exported"|"normal"|"structural". */const char *status;diff --git a/tests/test_httpd.c b/tests/test_httpd.cindex ec0490c50..d66799004 100644--- a/tests/test_httpd.c+++ b/tests/test_httpd.c@@ -1191,8 +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", "/api/metrics", "/api/trace"};+ static const char *const routes[] = {"/api/tree", "/api/symbol", "/api/flows", "/api/flow",+ "/api/metrics", "/api/trace", "/api/scent"};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 0647b3fab..0013bb35b 100644--- a/tests/test_ui.c+++ b/tests/test_ui.c@@ -1452,6 +1452,51 @@ TEST(atlas_symbol_data_flows_and_history_shape) {PASS();}+TEST(atlas_scent_buckets_matches_by_region) {+ cbm_layout_regions_cache_clear();+ cbm_store_t *store = atlas_fixture(NULL);+ ASSERT_NOT_NULL(store);++ /* "alpha" matches the three alpha_* functions (one region) plus+ * test_alpha_one in the tests folder region — File nodes are excluded+ * so a file does not double-count its own symbols. */+ char *json = cbm_atlas_scent_json(store, "regions-test", "alpha");+ 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);+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(root, "total")), 4);+ yyjson_val *regions = yyjson_obj_get(root, "regions");+ int max_count = 0;+ long long bucketed = 0;+ for (size_t i = 0; i < yyjson_arr_size(regions); i++) {+ int c = (int)yyjson_get_int(yyjson_obj_get(yyjson_arr_get(regions, i), "count"));+ bucketed += c;+ if (c > max_count)+ max_count = c;+ }+ ASSERT_EQ(max_count, 3);+ ASSERT_EQ((int)(bucketed + yyjson_get_int(yyjson_obj_get(root, "unmapped"))), 4);+ yyjson_doc_free(doc);+ free(json);++ json = cbm_atlas_scent_json(store, "regions-test", "_two");+ ASSERT_NOT_NULL(json);+ doc = yyjson_read(json, strlen(json), 0);+ root = yyjson_doc_get_root(doc);+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(root, "total")), 2);+ ASSERT_EQ((int)yyjson_arr_size(yyjson_obj_get(root, "regions")), 2);+ yyjson_doc_free(doc);+ free(json);++ /* Sub-2-char queries refuse rather than scan everything. */+ ASSERT_NULL(cbm_atlas_scent_json(store, "regions-test", "a"));++ cbm_store_close(store);+ cbm_layout_regions_cache_clear();+ PASS();+}+/* ── Suite ────────────────────────────────────────────────────── */SUITE(ui) {@@ -1491,4 +1536,5 @@ SUITE(ui) {RUN_TEST(atlas_metrics_totals_and_certainty);RUN_TEST(atlas_trace_reachability_calls_and_data);RUN_TEST(atlas_symbol_data_flows_and_history_shape);+ RUN_TEST(atlas_scent_buckets_matches_by_region);}