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 CBM Atlas screens — Overview, Modules, Symbol, Flows, Changes, search, prompt composer
Martin Vogel8bcb308e282f
diff --git a/graph-ui/src/App.tsx b/graph-ui/src/App.tsxindex 2cd1b72ee..6d21ad144 100644--- a/graph-ui/src/App.tsx+++ b/graph-ui/src/App.tsx@@ -2,171 +2,279 @@ import { useCallback, useEffect, useState } from "react";import { GraphTab } from "./components/GraphTab";import { StatsTab } from "./components/StatsTab";import { ControlTab } from "./components/ControlTab";+import { OverviewTab } from "./components/OverviewTab";+import { ModulesTab } from "./components/ModulesTab";+import { SymbolTab } from "./components/SymbolTab";+import { FlowsTab } from "./components/FlowsTab";+import { ChangesTab } from "./components/ChangesTab";+import { CommandK } from "./components/CommandK";+import {+ PromptBasketProvider,+ PromptBasketDrawer,+} from "./components/PromptBasket";import type { TabId } from "./lib/types";import { useUiMessages } from "./lib/i18n";-const TAB_IDS: TabId[] = ["graph", "stats", "control"];+const TAB_IDS: TabId[] = [+ "overview",+ "modules",+ "graph",+ "flows",+ "changes",+ "symbol",+ "stats",+ "control",+];++/* Tabs that need a selected project. "symbol" is reachable only via links. */+const PROJECT_TABS: TabId[] = ["overview", "modules", "graph", "flows", "changes"];interface RouteState {tab: TabId;project: string | null;- /* Deep links: a selected node and/or an opened region survive reloads and- * can be shared (#564). Values are the server-assigned ids. */+ /* Deep links (#564): node/region on the galaxy, sym on the symbol page,+ * path in Modules, flow in Flows — all survive reloads and sharing. */node: string | null;region: string | null;+ sym: string | null;+ path: string;+ flow: string | null;}-/* Read the active tab + selected project from the URL query string so the- * current view survives refreshes and can be bookmarked or shared. */function readRoute(): RouteState {const params = new URLSearchParams(window.location.search);const rawTab = params.get("tab");const tab = TAB_IDS.includes(rawTab as TabId) ? (rawTab as TabId) : "stats";- const project = params.get("project");- const node = params.get("node");- const region = params.get("region");return {tab,- project: project ? project : null,- node: node ? node : null,- region: region ? region : null,+ project: params.get("project") || null,+ node: params.get("node") || null,+ region: params.get("region") || null,+ sym: params.get("sym") || null,+ path: params.get("path") || "",+ flow: params.get("flow") || null,};}-/* Build the canonical URL for a route, preserving the path and hash. */-function routeUrl(- tab: TabId,- project: string | null,- node?: string | null,- region?: string | null,-): string {+function routeUrl(route: RouteState): string {const params = new URLSearchParams();- params.set("tab", tab);- if (project) params.set("project", project);- if (region) params.set("region", region);- if (node) params.set("node", node);+ params.set("tab", route.tab);+ if (route.project) params.set("project", route.project);+ if (route.region) params.set("region", route.region);+ if (route.node) params.set("node", route.node);+ if (route.sym) params.set("sym", route.sym);+ if (route.path) params.set("path", route.path);+ if (route.flow) params.set("flow", route.flow);return `${window.location.pathname}?${params.toString()}${window.location.hash}`;}export function App() {const t = useUiMessages();const [route, setRoute] = useState<RouteState>(readRoute);+ const [commandOpen, setCommandOpen] = useState(false);const { tab: activeTab, project: selectedProject } = route;- /* Normalize the URL on first load so it always carries the current route. */useEffect(() => {const initial = readRoute();- window.history.replaceState(- null,- "",- routeUrl(initial.tab, initial.project, initial.node, initial.region),- );+ window.history.replaceState(null, "", routeUrl(initial));}, []);- /* Sync state when the user navigates with the browser back/forward buttons. */useEffect(() => {const onPopState = () => setRoute(readRoute());window.addEventListener("popstate", onPopState);return () => window.removeEventListener("popstate", onPopState);}, []);- /* Change the route and push a history entry (skips no-op navigations). */- const navigate = useCallback(- (- tab: TabId,- project: string | null,- node: string | null = null,- region: string | null = null,- ) => {- const url = routeUrl(tab, project, node, region);+ /* ⌘K / ctrl-K anywhere. */+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {+ event.preventDefault();+ setCommandOpen((value) => !value);+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);++ const navigate = useCallback((next: Partial<RouteState> & { tab: TabId }) => {+ setRoute((previous) => {+ const merged: RouteState = {+ project: previous.project,+ node: null,+ region: null,+ sym: null,+ path: "",+ flow: null,+ ...next,+ } as RouteState;+ const url = routeUrl(merged);const current = `${window.location.pathname}${window.location.search}${window.location.hash}`;- if (url === current) return;- window.history.pushState(null, "", url);- setRoute({ tab, project, node, region });+ if (url !== current) window.history.pushState(null, "", url);+ return merged;+ });+ }, []);++ const openSymbol = useCallback(+ (ref: { id?: number; qn?: string }) => {+ navigate({+ tab: "symbol",+ sym: ref.qn ?? (ref.id !== undefined ? `#${ref.id}` : null),+ });+ },+ [navigate],+ );+ const openRegion = useCallback(+ (regionId: number) => {+ navigate({ tab: "graph", region: String(regionId) });},- [],+ [navigate],);const tabs: { id: TabId; label: string }[] = [- { id: "graph", label: t.tabs.graph },+ { id: "overview", label: "Overview" },+ { id: "modules", label: "Modules" },+ { id: "graph", label: "Galaxy" },+ { id: "flows", label: "Flows" },+ { id: "changes", label: "Changes" },{ id: "stats", label: t.tabs.projects },{ id: "control", label: t.tabs.control },];+ const symbolRef = route.sym+ ? route.sym.startsWith("#")+ ? { id: Number(route.sym.slice(1)) }+ : { qn: route.sym }+ : null;+return (- <div className="h-screen flex flex-col bg-background text-foreground">- {/* Header */}- <header className="flex items-center justify-between px-5 h-12 border-b border-border bg-[#0b1920]/80 backdrop-blur-md shrink-0">- <div className="flex items-center gap-6">- <div className="flex items-center gap-2.5">- <div className="w-[7px] h-[7px] rounded-full bg-primary" />- <span className="text-[13px] font-semibold text-foreground/90 tracking-tight">- CBM Atlas- </span>+ <PromptBasketProvider>+ <div className="h-screen flex flex-col bg-background text-foreground">+ {/* Header */}+ <header className="flex items-center justify-between px-5 h-12 border-b border-border bg-[#0b1920]/80 backdrop-blur-md shrink-0">+ <div className="flex items-center gap-6 min-w-0">+ <div className="flex items-center gap-2.5 shrink-0">+ <div className="w-[7px] h-[7px] rounded-full bg-primary" />+ <span className="text-[13px] font-semibold text-foreground/90 tracking-tight">+ CBM Atlas+ </span>+ </div>++ <nav className="flex items-center gap-0.5 overflow-x-auto">+ {tabs.map((tab) => {+ const disabled = PROJECT_TABS.includes(tab.id) && !selectedProject;+ return (+ <button+ key={tab.id}+ onClick={() =>+ navigate({+ tab: tab.id,+ project: tab.id === "stats" ? null : selectedProject,+ })+ }+ disabled={disabled}+ title={disabled ? "Select a project first" : undefined}+ className={`px-3 py-1 rounded-md text-[12px] font-medium transition-all whitespace-nowrap ${+ disabled+ ? "text-muted-foreground/30 cursor-not-allowed"+ : activeTab === tab.id+ ? "bg-primary/15 text-primary"+ : "text-muted-foreground hover:text-foreground hover:bg-white/[0.04]"+ }`}+ >+ {tab.label}+ </button>+ );+ })}+ </nav></div>- {/* Tabs inline in header */}- <nav className="flex items-center gap-0.5">- {tabs.map((tab) => {- const disabled = tab.id === "graph" && !selectedProject;- return (- <button- key={tab.id}- onClick={() => navigate(tab.id, tab.id === "stats" ? null : selectedProject)}- disabled={disabled}- title={disabled ? "Select a project first" : undefined}- className={`px-3 py-1 rounded-md text-[12px] font-medium transition-all ${- disabled- ? "text-muted-foreground/30 cursor-not-allowed"- : activeTab === tab.id- ? "bg-primary/15 text-primary"- : "text-muted-foreground hover:text-foreground hover:bg-white/[0.04]"- }`}- >- {tab.label}- </button>- );- })}- </nav>- </div>-- {selectedProject && (- <div className="flex items-center gap-2 px-3 py-1 rounded-lg bg-white/[0.04] border border-border/30">- <span className="text-[10px] text-foreground/30 uppercase tracking-wider">- {t.graph.selectedLabel}- </span>- <span className="text-[11px] text-primary font-mono truncate max-w-[300px]">- {selectedProject}- </span>+ <div className="flex items-center gap-2 shrink-0"><button- onClick={() => navigate("stats", null)}- className="text-foreground/20 hover:text-foreground/50 text-[12px] ml-1 transition-colors"+ onClick={() => setCommandOpen(true)}+ className="px-2.5 py-1 rounded-md text-[11px] text-muted-foreground hover:text-foreground bg-white/[0.03] hover:bg-white/[0.06] border border-border/40 transition-all"+ title="Search symbols and code">- ×+ ⌘K</button>+ {selectedProject && (+ <div className="flex items-center gap-2 px-3 py-1 rounded-lg bg-white/[0.04] border border-border/30">+ <span className="text-[11px] text-primary font-mono truncate max-w-[240px]">+ {selectedProject}+ </span>+ <button+ onClick={() => navigate({ tab: "stats", project: null })}+ className="text-foreground/20 hover:text-foreground/50 text-[12px] transition-colors"+ >+ ×+ </button>+ </div>+ )}</div>- )}- </header>-- {/* Content */}- <main className="flex-1 min-h-0">- {activeTab === "graph" ? (- <GraphTab- project={selectedProject}- routeNode={route.node}- routeRegion={route.region}- onRouteChange={(node, region) =>- navigate("graph", selectedProject, node, region)- }- />- ) : activeTab === "control" ? (- <ControlTab />- ) : (- <StatsTab- onSelectProject={(p) => navigate("graph", p)}- />- )}- </main>- </div>+ </header>++ {/* Content */}+ <main className="flex-1 min-h-0">+ {activeTab === "overview" && selectedProject ? (+ <OverviewTab+ project={selectedProject}+ onOpenRegion={openRegion}+ onOpenSymbol={(qn) => openSymbol({ qn })}+ onOpenModules={() => navigate({ tab: "modules" })}+ onOpenFlows={() => navigate({ tab: "flows" })}+ />+ ) : activeTab === "modules" && selectedProject ? (+ <ModulesTab+ project={selectedProject}+ path={route.path}+ onNavigatePath={(path) => navigate({ tab: "modules", path })}+ onOpenSymbol={openSymbol}+ onOpenRegion={openRegion}+ />+ ) : activeTab === "graph" ? (+ <GraphTab+ project={selectedProject}+ routeNode={route.node}+ routeRegion={route.region}+ onRouteChange={(node, region) =>+ navigate({ tab: "graph", node, region })+ }+ />+ ) : activeTab === "flows" && selectedProject ? (+ <FlowsTab+ project={selectedProject}+ flowId={route.flow !== null ? Number(route.flow) : null}+ onOpenFlow={(id) =>+ navigate({ tab: "flows", flow: id !== null ? String(id) : null })+ }+ onOpenSymbol={openSymbol}+ />+ ) : activeTab === "changes" && selectedProject ? (+ <ChangesTab project={selectedProject} onOpenSymbol={openSymbol} />+ ) : activeTab === "symbol" && selectedProject && symbolRef ? (+ <SymbolTab+ project={selectedProject}+ symbolRef={symbolRef}+ onOpenSymbol={openSymbol}+ onOpenRegion={openRegion}+ />+ ) : activeTab === "control" ? (+ <ControlTab />+ ) : (+ <StatsTab+ onSelectProject={(project) => navigate({ tab: "overview", project })}+ />+ )}+ </main>++ <CommandK+ project={selectedProject}+ open={commandOpen}+ onClose={() => setCommandOpen(false)}+ onOpenSymbol={openSymbol}+ />+ <PromptBasketDrawer project={selectedProject} />+ </div>+ </PromptBasketProvider>);}diff --git a/graph-ui/src/components/ChangesTab.tsx b/graph-ui/src/components/ChangesTab.tsxnew file mode 100644index 000000000..18c14ecb5--- /dev/null+++ b/graph-ui/src/components/ChangesTab.tsx@@ -0,0 +1,173 @@+/* Changes — what am I about to break: detect_changes on the working tree,+ * grouped by risk, every affected symbol one click from its page and the+ * whole blast radius one click from the prompt composer. */+import { useEffect, useMemo, useState } from "react";+import { ScrollArea } from "@/components/ui/scroll-area";+import { fetchChanges, archRows, type ArchitectureJson } from "../lib/atlas";+import { usePromptBasket } from "./PromptBasket";++interface ChangesTabProps {+ project: string;+ onOpenSymbol: (ref: { id?: number; qn?: string }) => void;+}++interface AffectedRow {+ qn?: string;+ symbol?: string;+ file?: string;+ risk?: string;+ hops?: number;+ [key: string]: string | number | null | undefined;+}++const RISK_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];+const RISK_TONE: Record<string, string> = {+ CRITICAL: "text-red-300/90 border-red-300/40 bg-red-400/10",+ HIGH: "text-amber-300/90 border-amber-300/40 bg-amber-400/10",+ MEDIUM: "text-sky-300/80 border-sky-300/30 bg-sky-400/5",+ LOW: "text-foreground/50 border-border/40 bg-white/[0.02]",+};++export function ChangesTab({ project, onOpenSymbol }: ChangesTabProps) {+ const [result, setResult] = useState<ArchitectureJson | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);+ const basket = usePromptBasket();++ const run = () => {+ setLoading(true);+ setError(null);+ fetchChanges(project)+ .then(setResult)+ .catch((err) => setError(err instanceof Error ? err.message : "failed"))+ .finally(() => setLoading(false));+ };++ useEffect(() => {+ setResult(null);+ setError(null);+ }, [project]);++ const sections = useMemo(() => {+ if (!result) return [];+ /* detect_changes(format:"json") emits {cols, rows} sections; collect+ * whichever carry symbol-shaped rows, keep scalars as banner text. */+ return Object.entries(result)+ .filter(([, value]) => typeof value === "object" && value !== null && "cols" in value)+ .map(([name]) => ({ name, rows: archRows<AffectedRow>(result, name) }))+ .filter((section) => section.rows.length > 0);+ }, [result]);++ const scalars = useMemo(() => {+ if (!result) return [];+ return Object.entries(result).filter(+ ([, value]) => typeof value === "string" || typeof value === "number",+ ) as [string, string | number][];+ }, [result]);++ const riskOf = (row: AffectedRow): string => String(row.risk ?? "LOW").toUpperCase();+ const qnOf = (row: AffectedRow): string | undefined =>+ (row.qn as string) ?? (row.symbol as string) ?? undefined;++ const affected = useMemo(() => {+ const rows = sections.flatMap((section) => section.rows).filter((row) => qnOf(row));+ return [...rows].sort(+ (a, b) => RISK_ORDER.indexOf(riskOf(a)) - RISK_ORDER.indexOf(riskOf(b)),+ );+ }, [sections]);++ return (+ <ScrollArea className="h-full">+ <div className="max-w-[1000px] mx-auto px-6 py-6">+ <div className="flex items-center gap-3 mb-4 flex-wrap">+ <h2 className="text-[16px] font-semibold text-foreground/90">+ Working-tree impact+ </h2>+ <button+ onClick={run}+ disabled={loading}+ className="px-3 py-1.5 rounded-md bg-primary/15 text-primary text-[12px] font-medium hover:bg-primary/25 transition-colors disabled:opacity-40"+ >+ {loading ? "Analyzing…" : result ? "Re-analyze" : "Analyze my uncommitted changes"}+ </button>+ {affected.length > 0 && (+ <button+ onClick={() => {+ for (const row of affected.slice(0, 20)) {+ const qn = qnOf(row)!;+ basket.add({+ kind: "symbol",+ id: -1 - affected.indexOf(row),+ name: qn.split(".").pop() ?? qn,+ qualified_name: qn,+ file_path: (row.file as string) ?? undefined,+ });+ }+ }}+ className="px-3 py-1.5 rounded-md bg-white/[0.05] text-foreground/60 text-[12px] font-medium hover:bg-white/[0.09] transition-colors"+ >+ Cite blast radius in prompt+ </button>+ )}+ </div>++ {error && <p className="text-red-400/80 text-[12px] mb-3">{error}</p>}+ {!result && !loading && !error && (+ <p className="text-[12.5px] text-foreground/40 max-w-[65ch] leading-relaxed">+ Runs <span className="font-mono text-foreground/60">detect_changes</span> against the+ project's git working tree: changed symbols, their transitive callers with risk+ classification, and the tests that cover them — the map to read before asking an+ agent to finish a refactor.+ </p>+ )}++ {scalars.length > 0 && (+ <div className="flex flex-wrap gap-4 mb-4">+ {scalars.map(([key, value]) => (+ <div key={key}>+ <p className="text-[9px] uppercase tracking-widest text-foreground/25">+ {key.replace(/_/g, " ")}+ </p>+ <p className="text-[13px] text-foreground/70 tabular-nums">{String(value)}</p>+ </div>+ ))}+ </div>+ )}++ {result && affected.length === 0 && (+ <p className="text-[12px] text-foreground/40">+ No affected symbols — the working tree is clean or the changes touch nothing indexed.+ </p>+ )}++ {affected.length > 0 && (+ <div className="space-y-px">+ {affected.map((row, index) => {+ const risk = riskOf(row);+ const qn = qnOf(row)!;+ return (+ <button+ key={`${qn}-${index}`}+ onClick={() => onOpenSymbol({ qn })}+ className="flex items-center gap-2.5 w-full text-left px-2 py-[5px] rounded-md hover:bg-white/[0.04] transition-colors group"+ >+ <span+ className={`text-[9px] px-1.5 py-0.5 rounded border shrink-0 ${RISK_TONE[risk] ?? RISK_TONE.LOW}`}+ >+ {risk}+ </span>+ <span className="text-[12px] font-mono text-foreground/70 group-hover:text-primary truncate transition-colors">+ {qn}+ </span>+ <span className="text-[10px] text-foreground/25 truncate ml-auto shrink-0 max-w-[35%]">+ {(row.file as string) ?? ""}+ </span>+ </button>+ );+ })}+ </div>+ )}+ </div>+ </ScrollArea>+ );+}diff --git a/graph-ui/src/components/CommandK.tsx b/graph-ui/src/components/CommandK.tsxnew file mode 100644index 000000000..bace9ef09--- /dev/null+++ b/graph-ui/src/components/CommandK.tsx@@ -0,0 +1,197 @@+/* ⌘K — one box, two engines: symbol names (search_graph) and code text+ * (search_code), grouped, keyboard-first. Enter opens, Esc closes. */+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { callTool } from "../api/rpc";+import { searchGraph, type SearchRow } from "../lib/atlas";++interface CommandKProps {+ project: string | null;+ open: boolean;+ onClose: () => void;+ onOpenSymbol: (ref: { qn: string }) => void;+}++interface TextHit {+ file: string;+ line: number;+ text: string;+}++/* search_code(format:"json") shape is tool-versioned; decode defensively. */+function decodeTextHits(payload: unknown): TextHit[] {+ const out: TextHit[] = [];+ const root = payload as {+ matches?: { file?: string; line?: number; text?: string }[];+ groups?: { file?: string; rows?: (string | number | null)[][] }[];+ };+ if (Array.isArray(root.matches)) {+ for (const match of root.matches)+ if (match.file)+ out.push({ file: match.file, line: match.line ?? 0, text: match.text ?? "" });+ } else if (Array.isArray(root.groups)) {+ for (const group of root.groups)+ for (const row of group.rows ?? [])+ out.push({+ file: group.file ?? "?",+ line: Number(row[0] ?? 0),+ text: String(row[1] ?? ""),+ });+ }+ return out.slice(0, 12);+}++export function CommandK({ project, open, onClose, onOpenSymbol }: CommandKProps) {+ const [query, setQuery] = useState("");+ const [symbols, setSymbols] = useState<SearchRow[]>([]);+ const [textHits, setTextHits] = useState<TextHit[]>([]);+ const [active, setActive] = useState(0);+ const [busy, setBusy] = useState(false);+ const inputRef = useRef<HTMLInputElement | null>(null);+ const seqRef = useRef(0);++ useEffect(() => {+ if (open) {+ setQuery("");+ setSymbols([]);+ setTextHits([]);+ setActive(0);+ setTimeout(() => inputRef.current?.focus(), 30);+ }+ }, [open]);++ useEffect(() => {+ if (!open || !project || query.trim().length < 2) {+ setSymbols([]);+ setTextHits([]);+ return;+ }+ const seq = ++seqRef.current;+ const timer = setTimeout(async () => {+ setBusy(true);+ const escaped = query.trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ const [nameResult, textResult] = await Promise.allSettled([+ searchGraph(project, { name_pattern: escaped, limit: 12 }),+ callTool("search_code", { project, query: query.trim(), limit: 12, format: "json" }),+ ]);+ if (seq !== seqRef.current) return;+ setSymbols(nameResult.status === "fulfilled" ? nameResult.value.rows : []);+ setTextHits(textResult.status === "fulfilled" ? decodeTextHits(textResult.value) : []);+ setActive(0);+ setBusy(false);+ }, 220);+ return () => clearTimeout(timer);+ }, [open, project, query]);++ const entries = useMemo(+ () =>+ [+ ...symbols.map((row) => ({ kind: "symbol" as const, row })),+ ...textHits.map((hit) => ({ kind: "text" as const, hit })),+ ],+ [symbols, textHits],+ );++ const activate = useCallback(+ (index: number) => {+ const entry = entries[index];+ if (!entry) return;+ if (entry.kind === "symbol") {+ onOpenSymbol({ qn: entry.row.qualified_name });+ onClose();+ }+ /* Text hits have no symbol identity; they stay informational. */+ },+ [entries, onOpenSymbol, onClose],+ );++ useEffect(() => {+ if (!open) return;+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") onClose();+ else if (event.key === "ArrowDown") {+ event.preventDefault();+ setActive((value) => Math.min(value + 1, entries.length - 1));+ } else if (event.key === "ArrowUp") {+ event.preventDefault();+ setActive((value) => Math.max(value - 1, 0));+ } else if (event.key === "Enter") {+ event.preventDefault();+ activate(active);+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [open, entries.length, active, activate, onClose]);++ if (!open) return null;++ return (+ <div+ className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm flex items-start justify-center pt-[12vh]"+ onClick={onClose}+ >+ <div+ className="w-[620px] max-w-[92vw] bg-[#0b1920] border border-border/60 rounded-xl shadow-2xl overflow-hidden"+ onClick={(event) => event.stopPropagation()}+ >+ <input+ ref={inputRef}+ type="text"+ placeholder={project ? "Search symbols and code…" : "Select a project first"}+ disabled={!project}+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ className="w-full bg-transparent px-4 py-3 text-[14px] text-foreground placeholder-foreground/25 outline-none border-b border-border/40"+ />+ <div className="max-h-[50vh] overflow-y-auto py-1">+ {busy && entries.length === 0 && (+ <p className="text-[11px] text-foreground/25 px-4 py-3">Searching…</p>+ )}+ {!busy && query.trim().length >= 2 && entries.length === 0 && (+ <p className="text-[11px] text-foreground/25 px-4 py-3">No matches.</p>+ )}+ {symbols.length > 0 && (+ <p className="px-4 pt-2 pb-1 text-[9px] uppercase tracking-widest text-foreground/25">+ Symbols+ </p>+ )}+ {symbols.map((row, index) => (+ <button+ key={row.qualified_name}+ onClick={() => activate(index)}+ onMouseEnter={() => setActive(index)}+ className={`flex items-center gap-2 w-full text-left px-4 py-[6px] transition-colors ${+ active === index ? "bg-primary/10" : ""+ }`}+ >+ <span className="text-[12px] font-mono text-foreground/75 truncate">{row.name}</span>+ <span className="text-[10px] text-foreground/30 shrink-0">{row.label}</span>+ <span className="text-[10px] text-foreground/20 truncate ml-auto max-w-[45%]">+ {row.file}+ </span>+ </button>+ ))}+ {textHits.length > 0 && (+ <p className="px-4 pt-2 pb-1 text-[9px] uppercase tracking-widest text-foreground/25">+ In code+ </p>+ )}+ {textHits.map((hit, index) => (+ <div+ key={`${hit.file}:${hit.line}:${index}`}+ className={`px-4 py-[5px] ${active === symbols.length + index ? "bg-primary/10" : ""}`}+ >+ <p className="text-[10px] font-mono text-foreground/35 truncate">+ {hit.file}:{hit.line}+ </p>+ <p className="text-[11px] font-mono text-foreground/60 truncate">{hit.text}</p>+ </div>+ ))}+ </div>+ <div className="px-4 py-2 border-t border-border/40 text-[10px] text-foreground/25">+ ↑↓ navigate · Enter opens the symbol · Esc closes+ </div>+ </div>+ </div>+ );+}diff --git a/graph-ui/src/components/FlowsTab.tsx b/graph-ui/src/components/FlowsTab.tsxnew file mode 100644index 000000000..829c41ac3--- /dev/null+++ b/graph-ui/src/components/FlowsTab.tsx@@ -0,0 +1,225 @@+/* Flows — how the codebase runs: ranked entry→terminal call journeys, each+ * opening as an indented call tree with every step one click from its+ * symbol page. Truncation is stated, never silent. */+import { useEffect, useMemo, useState } from "react";+import { ScrollArea } from "@/components/ui/scroll-area";+import {+ fetchFlow,+ fetchFlows,+ type FlowDetail,+ type FlowsPayload,+} from "../lib/atlas";+import { AddToPromptButton } from "./PromptBasket";++interface FlowsTabProps {+ project: string;+ flowId: number | null;+ onOpenFlow: (id: number | null) => void;+ onOpenSymbol: (ref: { id?: number; qn?: string }) => void;+}++function flowToMermaid(detail: FlowDetail): string {+ const lines = ["graph TD"];+ for (let index = 1; index < detail.steps.length; index++) {+ const step = detail.steps[index];+ const parent = detail.steps[step.parent];+ if (!parent) continue;+ const safe = (name: string) => name.replace(/[^A-Za-z0-9_]/g, "_");+ lines.push(` ${safe(parent.name)}${step.parent} --> ${safe(step.name)}${index}`);+ }+ return lines.join("\n");+}++export function FlowsTab({ project, flowId, onOpenFlow, onOpenSymbol }: FlowsTabProps) {+ const [payload, setPayload] = useState<FlowsPayload | null>(null);+ const [detail, setDetail] = useState<FlowDetail | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [copied, setCopied] = useState(false);++ useEffect(() => {+ let cancelled = false;+ setPayload(null);+ setError(null);+ fetchFlows(project)+ .then((flows) => {+ if (!cancelled) setPayload(flows);+ })+ .catch((err) => {+ if (!cancelled) setError(err instanceof Error ? err.message : "failed");+ });+ return () => {+ cancelled = true;+ };+ }, [project]);++ useEffect(() => {+ let cancelled = false;+ setDetail(null);+ if (flowId === null) return;+ fetchFlow(project, flowId)+ .then((flow) => {+ if (!cancelled) setDetail(flow);+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, [project, flowId]);++ const grouped = useMemo(() => {+ const flows = payload?.flows ?? [];+ return {+ cross: flows.filter((flow) => flow.cross_region),+ intra: flows.filter((flow) => !flow.cross_region),+ };+ }, [payload]);++ useEffect(() => {+ if (!copied) return;+ const timer = setTimeout(() => setCopied(false), 1500);+ return () => clearTimeout(timer);+ }, [copied]);++ if (error) {+ return (+ <div className="flex items-center justify-center h-full">+ <p className="text-red-400/80 text-sm">{error}</p>+ </div>+ );+ }+ if (!payload) {+ return (+ <div className="flex items-center justify-center h-full">+ <p className="text-white/30 text-sm">Tracing the journeys…</p>+ </div>+ );+ }++ return (+ <div className="h-full flex">+ {/* Flow list */}+ <div className="w-[380px] shrink-0 border-r border-border/40 flex flex-col bg-[#0b1920]/60">+ <div className="px-4 py-3 border-b border-border/30 shrink-0">+ <p className="text-[10px] uppercase tracking-widest text-foreground/30">+ Flows — entry → terminal+ </p>+ <p className="text-[10.5px] text-foreground/30 mt-1">+ {payload.flows.length} journeys from{" "}+ {payload.callable_total.toLocaleString("en-US")} callables+ {payload.candidates_dropped > 0 &&+ ` · ${payload.candidates_dropped.toLocaleString("en-US")} candidates not walked`}+ </p>+ </div>+ <ScrollArea className="flex-1 min-h-0">+ <div className="py-1">+ {(["cross", "intra"] as const).map((groupKey) => {+ const flows = grouped[groupKey];+ if (flows.length === 0) return null;+ return (+ <div key={groupKey}>+ <p className="px-4 pt-2 pb-1 text-[9px] uppercase tracking-widest text-foreground/25">+ {groupKey === "cross" ? "across regions" : "within one region"}+ </p>+ {flows.map((flow) => (+ <button+ key={flow.id}+ onClick={() => onOpenFlow(flow.id)}+ className={`flex items-center gap-2 w-full text-left px-4 py-[6px] transition-colors ${+ flowId === flow.id+ ? "bg-primary/10 text-primary"+ : "text-foreground/60 hover:text-foreground/85 hover:bg-white/[0.03]"+ }`}+ >+ <span className="text-[11.5px] font-mono truncate flex-1">{flow.label}</span>+ <span className="text-[10px] tabular-nums text-foreground/25 shrink-0">+ {flow.steps}+ </span>+ {!flow.sink_terminated && (+ <span className="text-[9px] text-foreground/20 shrink-0" title="walk stopped at the depth cap, not at a sink">+ …+ </span>+ )}+ </button>+ ))}+ </div>+ );+ })}+ {payload.flows.length === 0 && (+ <p className="text-[11px] text-foreground/25 px-4 py-4">+ No flows detected — the project may have no clear entry points.+ </p>+ )}+ </div>+ </ScrollArea>+ </div>++ {/* Flow detail */}+ <div className="flex-1 min-w-0">+ {flowId === null || !detail ? (+ <div className="flex items-center justify-center h-full">+ <p className="text-white/30 text-sm">+ {flowId === null ? "Pick a journey on the left" : "Loading…"}+ </p>+ </div>+ ) : (+ <ScrollArea className="h-full">+ <div className="px-6 py-5 max-w-[900px]">+ <div className="flex items-center gap-3 flex-wrap mb-1">+ <h3 className="text-[16px] font-semibold font-mono text-foreground/90">+ {detail.entry.name}+ <span className="text-foreground/30"> → </span>+ {detail.terminal.name}+ </h3>+ <AddToPromptButton+ item={{+ kind: "flow",+ id: detail.id,+ label: `${detail.entry.name} → ${detail.terminal.name}`,+ steps: detail.steps.length,+ }}+ />+ <button+ onClick={() => {+ navigator.clipboard?.writeText(flowToMermaid(detail)).then(() => setCopied(true));+ }}+ className="px-2.5 py-1 rounded-md bg-white/[0.05] text-foreground/60 text-[11px] font-medium hover:bg-white/[0.09] transition-colors"+ >+ {copied ? "Copied ✓" : "Copy as mermaid"}+ </button>+ </div>+ <p className="text-[11px] text-foreground/35 mb-4">+ {detail.steps.length} steps+ {detail.sink_terminated ? " · ends at a sink" : " · stopped at the depth cap"}+ {detail.cross_region ? " · crosses regions" : ""}+ {detail.steps_capped+ ? ` · ${detail.steps_capped} branches beyond the cap not shown`+ : ""}+ </p>++ <div className="space-y-px">+ {detail.steps.map((step, index) => (+ <button+ key={index}+ onClick={() => onOpenSymbol({ id: step.id })}+ className="flex items-center gap-2 w-full text-left py-[3.5px] rounded-md hover:bg-white/[0.04] transition-colors group"+ style={{ paddingLeft: `${step.depth * 22 + 8}px` }}+ >+ <span className="text-foreground/20 text-[10px] shrink-0">+ {step.depth === 0 ? "▶" : "└"}+ </span>+ <span className="text-[12px] font-mono text-foreground/70 group-hover:text-primary transition-colors truncate">+ {step.name}+ </span>+ <span className="text-[10px] text-foreground/20 truncate ml-auto shrink-0 max-w-[40%]">+ {step.file_path}+ </span>+ </button>+ ))}+ </div>+ </div>+ </ScrollArea>+ )}+ </div>+ </div>+ );+}diff --git a/graph-ui/src/components/ModulesTab.tsx b/graph-ui/src/components/ModulesTab.tsxnew file mode 100644index 000000000..dc25c6b07--- /dev/null+++ b/graph-ui/src/components/ModulesTab.tsx@@ -0,0 +1,319 @@+/* Modules — the territory: a squarified treemap of one folder's children,+ * sized by symbols, colored by dominant region, hatched when the indexer+ * missed files inside. Click a folder to drill, a file to list and open its+ * symbols. */+import { useCallback, useEffect, useMemo, useState } from "react";+import { fetchTree, type TreeChild, type TreePayload } from "../lib/atlas";+import { fetchRegions } from "../hooks/useGraphData";+import { squarify } from "../lib/treemap";+import { disambiguateRegionNames } from "../lib/regions";+import { searchGraph, type SearchRow } from "../lib/atlas";+import type { RegionsPayload } from "../lib/types";++interface ModulesTabProps {+ project: string;+ path: string;+ onNavigatePath: (path: string) => void;+ onOpenSymbol: (ref: { id?: number; qn?: string }) => void;+ onOpenRegion: (regionId: number) => void;+}++const NEUTRAL = "#39505f";++/* search_graph rows for one file, via the read-only /rpc surface. */+async function fetchFileSymbols(project: string, file: string): Promise<SearchRow[]> {+ const { rows } = await searchGraph(project, { file_pattern: file, limit: 200 });+ return rows;+}++export function ModulesTab({+ project,+ path,+ onNavigatePath,+ onOpenSymbol,+ onOpenRegion,+}: ModulesTabProps) {+ const [tree, setTree] = useState<TreePayload | null>(null);+ const [regions, setRegions] = useState<RegionsPayload | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [selectedFile, setSelectedFile] = useState<TreeChild | null>(null);+ const [fileSymbols, setFileSymbols] = useState<SearchRow[] | null>(null);+ const [size, setSize] = useState({ w: 900, h: 560 });++ useEffect(() => {+ let cancelled = false;+ setTree(null);+ setError(null);+ setSelectedFile(null);+ setFileSymbols(null);+ fetchTree(project, path)+ .then((payload) => {+ if (!cancelled) setTree(payload);+ })+ .catch((err) => {+ if (!cancelled) setError(err instanceof Error ? err.message : "failed");+ });+ return () => {+ cancelled = true;+ };+ }, [project, path]);++ useEffect(() => {+ let cancelled = false;+ fetchRegions(project)+ .then((payload) => {+ if (!cancelled) setRegions(payload);+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, [project]);++ const regionMeta = useMemo(() => {+ const map = new Map<number, { name: string; color: string }>();+ if (regions)+ for (const region of disambiguateRegionNames(regions.regions))+ map.set(region.id, { name: region.name, color: region.color });+ return map;+ }, [regions]);++ const rects = useMemo(() => {+ if (!tree) return [];+ const items = tree.children.map((child) => ({+ id: `${child.kind}:${child.path}`,+ value: Math.max(1, child.symbols),+ }));+ return squarify(items, 0, 0, size.w, size.h);+ }, [tree, size]);++ const childByKey = useMemo(() => {+ const map = new Map<string, TreeChild>();+ if (tree)+ for (const child of tree.children) map.set(`${child.kind}:${child.path}`, child);+ return map;+ }, [tree]);++ const openFile = useCallback(+ (child: TreeChild) => {+ setSelectedFile(child);+ setFileSymbols(null);+ fetchFileSymbols(project, child.path)+ .then(setFileSymbols)+ .catch(() => setFileSymbols([]));+ },+ [project],+ );++ const crumbs = useMemo(() => {+ const parts = path ? path.split("/") : [];+ return [{ label: "root", path: "" }].concat(+ parts.map((part, index) => ({+ label: part,+ path: parts.slice(0, index + 1).join("/"),+ })),+ );+ }, [path]);++ const measureRef = useCallback((element: HTMLDivElement | null) => {+ if (!element) return;+ const observer = new ResizeObserver((entries) => {+ for (const entry of entries) {+ const rect = entry.contentRect;+ if (rect.width > 100 && rect.height > 100)+ setSize({ w: rect.width, h: rect.height });+ }+ });+ observer.observe(element);+ }, []);++ if (error) {+ return (+ <div className="flex items-center justify-center h-full">+ <p className="text-red-400/80 text-sm">{error}</p>+ </div>+ );+ }++ return (+ <div className="h-full flex flex-col">+ {/* Breadcrumbs */}+ <div className="flex items-center gap-1 px-5 py-2.5 border-b border-border/30 shrink-0 flex-wrap">+ {crumbs.map((crumb, index) => (+ <span key={crumb.path} className="flex items-center gap-1">+ {index > 0 && <span className="text-foreground/20 text-[11px]">/</span>}+ <button+ onClick={() => onNavigatePath(crumb.path)}+ className={`text-[12px] transition-colors ${+ index === crumbs.length - 1+ ? "text-foreground/80 font-medium"+ : "text-foreground/40 hover:text-primary"+ }`}+ >+ {crumb.label}+ </button>+ </span>+ ))}+ {tree && (+ <span className="ml-auto text-[11px] text-foreground/30 font-mono">+ {tree.files.toLocaleString("en-US")} files ·{" "}+ {tree.symbols.toLocaleString("en-US")} symbols+ {tree.children_dropped ? ` · ${tree.children_dropped} children not shown` : ""}+ </span>+ )}+ </div>++ <div className="flex-1 min-h-0 flex">+ {/* Treemap */}+ <div ref={measureRef} className="flex-1 min-w-0 relative m-3">+ {!tree ? (+ <div className="flex items-center justify-center h-full">+ <p className="text-white/30 text-sm">Measuring the territory…</p>+ </div>+ ) : (+ <svg+ width="100%"+ height="100%"+ viewBox={`0 0 ${size.w} ${size.h}`}+ className="rounded-lg"+ role="img"+ aria-label={`Treemap of ${path || "the repository root"}`}+ >+ <defs>+ <pattern id="missed-hatch" width="7" height="7" patternTransform="rotate(45)" patternUnits="userSpaceOnUse">+ <rect width="7" height="7" fill="transparent" />+ <line x1="0" y1="0" x2="0" y2="7" stroke="#e9eef5" strokeOpacity="0.25" strokeWidth="2" />+ </pattern>+ </defs>+ {rects.map((rect) => {+ const child = childByKey.get(rect.id);+ if (!child) return null;+ const meta = child.region !== undefined ? regionMeta.get(child.region) : undefined;+ const fill = meta?.color ?? NEUTRAL;+ const showLabel = rect.w > 60 && rect.h > 24;+ return (+ <g+ key={rect.id}+ onClick={() =>+ child.kind === "dir" ? onNavigatePath(child.path) : openFile(child)+ }+ className="cursor-pointer"+ >+ <rect+ x={rect.x + 1}+ y={rect.y + 1}+ width={Math.max(0, rect.w - 2)}+ height={Math.max(0, rect.h - 2)}+ rx={3}+ fill={fill}+ fillOpacity={child.kind === "dir" ? 0.32 : 0.18}+ stroke={fill}+ strokeOpacity={0.55}+ >+ <title>+ {`${child.path} — ${child.symbols.toLocaleString("en-US")} symbols` ++ (child.kind === "dir" ? `, ${child.files} files` : "") ++ (meta ? `\nregion: ${meta.name}` : "") ++ (child.missed ? `\n${child.missed} file(s) not fully indexed` : "")}+ </title>+ </rect>+ {child.missed ? (+ <rect+ x={rect.x + 1}+ y={rect.y + 1}+ width={Math.max(0, rect.w - 2)}+ height={Math.max(0, rect.h - 2)}+ rx={3}+ fill="url(#missed-hatch)"+ pointerEvents="none"+ />+ ) : null}+ {showLabel && (+ <text+ x={rect.x + 8}+ y={rect.y + 17}+ fill="#e4e4ed"+ fillOpacity={0.85}+ fontSize={11.5}+ fontFamily="ui-monospace, monospace"+ pointerEvents="none"+ >+ {child.kind === "dir" ? `${child.name}/` : child.name}+ </text>+ )}+ {showLabel && rect.h > 40 && (+ <text+ x={rect.x + 8}+ y={rect.y + 31}+ fill="#e4e4ed"+ fillOpacity={0.35}+ fontSize={9.5}+ fontFamily="ui-monospace, monospace"+ pointerEvents="none"+ >+ {child.symbols.toLocaleString("en-US")}+ </text>+ )}+ </g>+ );+ })}+ </svg>+ )}+ </div>++ {/* File panel */}+ {selectedFile && (+ <div className="w-[320px] shrink-0 border-l border-border/40 bg-[#0b1920]/90 flex flex-col">+ <div className="px-4 py-3 border-b border-border/30">+ <div className="flex items-start justify-between gap-2">+ <p className="text-[12px] font-mono text-foreground/80 break-all">+ {selectedFile.path}+ </p>+ <button+ onClick={() => setSelectedFile(null)}+ className="text-foreground/25 hover:text-foreground/60 text-[15px] leading-none"+ >+ ×+ </button>+ </div>+ <p className="text-[10px] text-foreground/30 mt-1">+ {selectedFile.symbols.toLocaleString("en-US")} symbols+ {selectedFile.missed ? " · not fully indexed" : ""}+ </p>+ </div>+ <div className="flex-1 min-h-0 overflow-y-auto py-1">+ {fileSymbols === null ? (+ <p className="text-[11px] text-foreground/25 px-4 py-3">Loading…</p>+ ) : fileSymbols.length === 0 ? (+ <p className="text-[11px] text-foreground/25 px-4 py-3">No symbols found.</p>+ ) : (+ fileSymbols.map((symbol) => (+ <button+ key={symbol.qualified_name}+ onClick={() => onOpenSymbol({ qn: symbol.qualified_name })}+ className="flex items-center gap-2 w-full text-left px-4 py-[4px] text-[11px] hover:bg-white/[0.04] transition-colors group"+ >+ <span className="font-mono text-foreground/60 group-hover:text-primary truncate transition-colors">+ {symbol.name}+ </span>+ <span className="text-foreground/20 text-[10px] ml-auto shrink-0">+ {symbol.label}+ </span>+ </button>+ ))+ )}+ </div>+ {selectedFile.region !== undefined && regionMeta.get(selectedFile.region) && (+ <button+ onClick={() => onOpenRegion(selectedFile.region!)}+ className="px-4 py-2.5 border-t border-border/30 text-left text-[11px] text-primary/70 hover:text-primary transition-colors"+ >+ region: {regionMeta.get(selectedFile.region)!.name} — view in galaxy →+ </button>+ )}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/graph-ui/src/components/OverviewTab.tsx b/graph-ui/src/components/OverviewTab.tsxnew file mode 100644index 000000000..ee50ffd13--- /dev/null+++ b/graph-ui/src/components/OverviewTab.tsx@@ -0,0 +1,314 @@+/* Overview — the first read of a project: freshness, the map of regions,+ * hubs, entry points, boundaries, surprising couplings and suggested+ * questions. Everything deterministic, everything with a why, everything+ * one click from detail or from the prompt composer. */+import { useEffect, useMemo, useState } from "react";+import { ScrollArea } from "@/components/ui/scroll-area";+import { fetchArchitecture, archRows, type ArchitectureJson } from "../lib/atlas";+import { fetchRegions } from "../hooks/useGraphData";+import { disambiguateRegionNames } from "../lib/regions";+import { surprisingCouplings, suggestedQuestions } from "../lib/firstread";+import { AddToPromptButton } from "./PromptBasket";+import type { RegionsPayload } from "../lib/types";++interface OverviewTabProps {+ project: string;+ onOpenRegion: (regionId: number) => void;+ onOpenSymbol: (qn: string) => void;+ onOpenModules: () => void;+ onOpenFlows: () => void;+}++interface HotspotRow {+ qn: string;+ fan_in: number;+}+interface EntryRow {+ qn: string;+ file: string;+}+interface BoundaryRow {+ from: string;+ to: string;+ calls: number;+}+interface LanguageRow {+ language: string;+ files: number;+}++function shortQn(qn: string): string {+ const parts = qn.split(".");+ return parts.slice(-2).join(".");+}++function Card({ title, children, wide }: { title: string; children: React.ReactNode; wide?: boolean }) {+ return (+ <div className={`bg-white/[0.02] border border-border/40 rounded-xl p-4 ${wide ? "col-span-full" : ""}`}>+ <p className="text-[10px] uppercase tracking-widest text-foreground/30 mb-3">{title}</p>+ {children}+ </div>+ );+}++export function OverviewTab({+ project,+ onOpenRegion,+ onOpenSymbol,+ onOpenModules,+ onOpenFlows,+}: OverviewTabProps) {+ const [arch, setArch] = useState<ArchitectureJson | null>(null);+ const [regions, setRegions] = useState<RegionsPayload | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ setArch(null);+ setRegions(null);+ setError(null);+ Promise.allSettled([fetchArchitecture(project), fetchRegions(project)]).then(+ ([archResult, regionsResult]) => {+ if (cancelled) return;+ if (archResult.status === "fulfilled") setArch(archResult.value);+ if (regionsResult.status === "fulfilled") setRegions(regionsResult.value);+ if (archResult.status === "rejected" && regionsResult.status === "rejected")+ setError(String(archResult.reason?.message ?? "failed to load"));+ },+ );+ return () => {+ cancelled = true;+ };+ }, [project]);++ const displayRegions = useMemo(+ () => (regions ? disambiguateRegionNames(regions.regions) : []),+ [regions],+ );+ const couplings = useMemo(() => (regions ? surprisingCouplings(regions, 4) : []), [regions]);+ const questions = useMemo(() => (regions ? suggestedQuestions(regions, {}, 4) : []), [regions]);++ const hotspots = useMemo(() => archRows<HotspotRow>(arch, "hotspots"), [arch]);+ const entries = useMemo(() => archRows<EntryRow>(arch, "entry_points"), [arch]);+ const boundaries = useMemo(() => archRows<BoundaryRow>(arch, "boundaries"), [arch]);+ const languages = useMemo(() => archRows<LanguageRow>(arch, "languages"), [arch]);+ const totalNodes = typeof arch?.total_nodes === "number" ? arch.total_nodes : regions?.total_nodes;+ const totalEdges = typeof arch?.total_edges === "number" ? arch.total_edges : undefined;++ if (error) {+ return (+ <div className="flex items-center justify-center h-full">+ <p className="text-red-400/80 text-sm">{error}</p>+ </div>+ );+ }+ if (!arch && !regions) {+ return (+ <div className="flex items-center justify-center h-full">+ <p className="text-white/30 text-sm">Reading the map…</p>+ </div>+ );+ }++ return (+ <ScrollArea className="h-full">+ <div className="max-w-[1200px] mx-auto px-6 py-6">+ {/* Header numbers */}+ <div className="flex flex-wrap gap-6 mb-6">+ {[+ { label: "Symbols", value: totalNodes?.toLocaleString("en-US") ?? "…" },+ { label: "Edges", value: totalEdges?.toLocaleString("en-US") ?? "…" },+ { label: "Regions", value: displayRegions.length || "…" },+ {+ label: "Languages",+ value:+ languages+ .slice(0, 3)+ .map((lang) => lang.language)+ .join(" · ") || "…",+ },+ ].map((stat) => (+ <div key={stat.label}>+ <p className="text-[9px] uppercase tracking-widest text-foreground/25">{stat.label}</p>+ <p className="text-[17px] font-semibold text-foreground/90 tabular-nums">+ {stat.value}+ </p>+ </div>+ ))}+ {regions && regions.unmapped_nodes > 0 && (+ <div>+ <p className="text-[9px] uppercase tracking-widest text-foreground/25">Unmapped</p>+ <p className="text-[17px] font-semibold text-amber-300/70 tabular-nums">+ {regions.unmapped_nodes.toLocaleString("en-US")}+ </p>+ </div>+ )}+ </div>++ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ {/* Regions — the map */}+ <Card title={`Regions — the de-facto modules (${regions?.method ?? "…"})`} wide>+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">+ {displayRegions.slice(0, 12).map((region) => (+ <button+ key={region.id}+ onClick={() => onOpenRegion(region.id)}+ className="text-left rounded-lg border border-border/30 bg-white/[0.02] hover:bg-white/[0.05] hover:border-primary/30 p-3 transition-all group"+ >+ <div className="flex items-center gap-2 mb-1">+ <span+ className="w-2 h-2 rounded-full shrink-0"+ style={{ backgroundColor: region.color }}+ />+ <span className="text-[12px] font-medium text-foreground/80 truncate group-hover:text-primary transition-colors">+ {region.name}+ </span>+ </div>+ <p className="text-[10px] text-foreground/30 truncate">+ {region.members.toLocaleString("en-US")} symbols · cohesion{" "}+ {region.cohesion.toFixed(2)}+ </p>+ {region.why && (+ <p className="text-[10px] text-foreground/25 mt-1 line-clamp-2">{region.why}</p>+ )}+ </button>+ ))}+ </div>+ {displayRegions.length > 12 && (+ <button+ onClick={onOpenModules}+ className="mt-2 text-[11px] text-primary/70 hover:text-primary transition-colors"+ >+ all {displayRegions.length} regions in Modules →+ </button>+ )}+ </Card>++ {/* Hubs */}+ <Card title="Hubs — highest fan-in">+ <div className="space-y-px">+ {hotspots.slice(0, 8).map((hotspot) => (+ <div key={hotspot.qn} className="flex items-center gap-2 py-[3px]">+ <button+ onClick={() => onOpenSymbol(hotspot.qn)}+ className="text-[11px] font-mono text-foreground/60 hover:text-primary truncate flex-1 text-left transition-colors"+ title={hotspot.qn}+ >+ {shortQn(hotspot.qn)}+ </button>+ <span className="text-[10px] tabular-nums text-foreground/30 shrink-0">+ {Number(hotspot.fan_in).toLocaleString("en-US")}+ </span>+ </div>+ ))}+ {hotspots.length === 0 && (+ <p className="text-[11px] text-foreground/25">No hotspot data.</p>+ )}+ </div>+ </Card>++ {/* Start here */}+ <Card title="Start here — entry points">+ <div className="space-y-px">+ {entries.slice(0, 8).map((entry) => (+ <button+ key={entry.qn}+ onClick={() => onOpenSymbol(entry.qn)}+ className="flex items-center gap-2 w-full text-left py-[3px] group"+ title={entry.qn}+ >+ <span className="text-[11px] font-mono text-foreground/60 group-hover:text-primary truncate transition-colors">+ {shortQn(entry.qn)}+ </span>+ <span className="text-[10px] text-foreground/20 truncate ml-auto shrink-0 max-w-[40%]">+ {entry.file}+ </span>+ </button>+ ))}+ {entries.length === 0 && (+ <p className="text-[11px] text-foreground/25">No entry points detected.</p>+ )}+ </div>+ <button+ onClick={onOpenFlows}+ className="mt-2 text-[11px] text-primary/70 hover:text-primary transition-colors"+ >+ follow them in Flows →+ </button>+ </Card>++ {/* Surprising couplings */}+ <Card title="Surprising couplings — with reasons">+ <div className="space-y-2">+ {couplings.map((coupling) => (+ <div key={`${coupling.source.id}-${coupling.target.id}`}>+ <p className="text-[11.5px] text-foreground/70">+ <span className="font-medium">{coupling.source.name}</span>+ <span className="text-foreground/30"> ⇄ </span>+ <span className="font-medium">{coupling.target.name}</span>+ </p>+ <p className="text-[10px] text-foreground/30">{coupling.reasons.join(" · ")}</p>+ </div>+ ))}+ {couplings.length === 0 && (+ <p className="text-[11px] text-foreground/25">+ No cross-region couplings stand out.+ </p>+ )}+ </div>+ </Card>++ {/* Suggested questions */}+ <Card title="Questions this graph can answer — ask your agent">+ <div className="space-y-2">+ {questions.map((question) => (+ <div key={question.question} className="flex items-start gap-2">+ <div className="flex-1 min-w-0">+ <p className="text-[11.5px] text-foreground/70">{question.question}</p>+ <p className="text-[10px] text-foreground/30">{question.why}</p>+ </div>+ <AddToPromptButton+ small+ item={{ kind: "question", question: question.question, why: question.why }}+ />+ </div>+ ))}+ {questions.length === 0 && (+ <p className="text-[11px] text-foreground/25">Nothing stands out structurally.</p>+ )}+ </div>+ </Card>++ {/* Boundaries */}+ <Card title="Boundaries — who calls across packages" wide>+ <div className="overflow-x-auto">+ <table className="w-full text-[11px]">+ <thead>+ <tr className="text-left text-[9px] uppercase tracking-wider text-foreground/25">+ <th className="py-1 pr-4 font-medium">from</th>+ <th className="py-1 pr-4 font-medium">to</th>+ <th className="py-1 text-right font-medium">calls</th>+ </tr>+ </thead>+ <tbody>+ {boundaries.slice(0, 8).map((boundary, index) => (+ <tr key={index} className="border-t border-border/20">+ <td className="py-1 pr-4 font-mono text-foreground/60">{boundary.from}</td>+ <td className="py-1 pr-4 font-mono text-foreground/60">{boundary.to}</td>+ <td className="py-1 text-right tabular-nums text-foreground/40">+ {Number(boundary.calls).toLocaleString("en-US")}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ {boundaries.length === 0 && (+ <p className="text-[11px] text-foreground/25">No cross-package calls recorded.</p>+ )}+ </div>+ </Card>+ </div>+ </div>+ </ScrollArea>+ );+}diff --git a/graph-ui/src/components/PromptBasket.tsx b/graph-ui/src/components/PromptBasket.tsxnew file mode 100644index 000000000..1e672fa1d--- /dev/null+++ b/graph-ui/src/components/PromptBasket.tsx@@ -0,0 +1,208 @@+/* The prompt composer: a basket of cited entities (symbols, regions, flows,+ * questions) that becomes a precise prompt for the user's coding agent —+ * the bridge from what the human learned to what the agent is told. */+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useState,+ type ReactNode,+} from "react";+import { composePrompt, basketKey, type BasketItem } from "../lib/composer";++interface BasketState {+ items: BasketItem[];+ add: (item: BasketItem) => void;+ remove: (key: string) => void;+ clear: () => void;+ open: boolean;+ setOpen: (open: boolean) => void;+}++const BasketContext = createContext<BasketState | null>(null);++const STORAGE_KEY = "cbm-atlas-basket";++export function PromptBasketProvider({ children }: { children: ReactNode }) {+ const [items, setItems] = useState<BasketItem[]>(() => {+ try {+ const raw = sessionStorage.getItem(STORAGE_KEY);+ return raw ? (JSON.parse(raw) as BasketItem[]) : [];+ } catch {+ return [];+ }+ });+ const [open, setOpen] = useState(false);++ useEffect(() => {+ try {+ sessionStorage.setItem(STORAGE_KEY, JSON.stringify(items));+ } catch {+ /* session storage unavailable — the basket still works in memory */+ }+ }, [items]);++ const add = useCallback((item: BasketItem) => {+ setItems((prev) =>+ prev.some((existing) => basketKey(existing) === basketKey(item))+ ? prev+ : [...prev, item],+ );+ setOpen(true);+ }, []);+ const remove = useCallback((key: string) => {+ setItems((prev) => prev.filter((item) => basketKey(item) !== key));+ }, []);+ const clear = useCallback(() => setItems([]), []);++ const value = useMemo(+ () => ({ items, add, remove, clear, open, setOpen }),+ [items, add, remove, clear, open],+ );+ return <BasketContext.Provider value={value}>{children}</BasketContext.Provider>;+}++export function usePromptBasket(): BasketState {+ const ctx = useContext(BasketContext);+ if (!ctx) throw new Error("usePromptBasket outside PromptBasketProvider");+ return ctx;+}++/* The standard "cite this" affordance. */+export function AddToPromptButton({ item, small }: { item: BasketItem; small?: boolean }) {+ const basket = usePromptBasket();+ const inBasket = basket.items.some((existing) => basketKey(existing) === basketKey(item));+ return (+ <button+ onClick={() => basket.add(item)}+ disabled={inBasket}+ className={`${small ? "px-1.5 py-0.5 text-[10px]" : "px-2.5 py-1 text-[11px]"} rounded-md font-medium transition-colors ${+ inBasket+ ? "bg-white/[0.04] text-foreground/25 cursor-default"+ : "bg-primary/15 text-primary hover:bg-primary/25"+ }`}+ title={inBasket ? "Already in the prompt" : "Cite this in the prompt composer"}+ >+ {inBasket ? "✓ cited" : "+ prompt"}+ </button>+ );+}++function itemLabel(item: BasketItem): string {+ switch (item.kind) {+ case "symbol":+ return item.qualified_name ?? item.name;+ case "region":+ return `region ${item.name}`;+ case "flow":+ return `flow ${item.label}`;+ case "question":+ return item.question;+ }+}++/* The drawer: goal text + cited items + the composed prompt with copy. */+export function PromptBasketDrawer({ project }: { project: string | null }) {+ const basket = usePromptBasket();+ const [goal, setGoal] = useState("");+ const [copied, setCopied] = useState(false);+ const prompt = useMemo(+ () => composePrompt(project ?? "?", goal, basket.items),+ [project, goal, basket.items],+ );++ useEffect(() => {+ if (!copied) return;+ const timer = setTimeout(() => setCopied(false), 1500);+ return () => clearTimeout(timer);+ }, [copied]);++ if (!basket.open) {+ return (+ <button+ onClick={() => basket.setOpen(true)}+ className="fixed bottom-4 right-4 z-40 px-3 py-2 rounded-full bg-primary/20 text-primary text-[12px] font-medium border border-primary/30 backdrop-blur-md hover:bg-primary/30 transition-colors shadow-lg"+ >+ Prompt {basket.items.length > 0 ? `(${basket.items.length})` : ""}+ </button>+ );+ }++ return (+ <div className="fixed bottom-0 right-0 z-40 w-full sm:w-[440px] max-h-[70vh] bg-[#0b1920]/98 border-l border-t border-border/60 rounded-tl-xl backdrop-blur-xl flex flex-col shadow-2xl">+ <div className="flex items-center justify-between px-4 py-2.5 border-b border-border/40">+ <span className="text-[12px] font-semibold text-foreground/80">+ Prompt composer <span className="text-foreground/30">({basket.items.length} cited)</span>+ </span>+ <div className="flex gap-2 items-center">+ {basket.items.length > 0 && (+ <button+ onClick={basket.clear}+ className="text-[11px] text-foreground/30 hover:text-foreground/60 transition-colors"+ >+ clear+ </button>+ )}+ <button+ onClick={() => basket.setOpen(false)}+ className="text-foreground/25 hover:text-foreground/60 text-[15px] leading-none transition-colors"+ >+ ×+ </button>+ </div>+ </div>++ <div className="px-4 py-2.5 border-b border-border/30">+ <input+ type="text"+ placeholder="What do you want your agent to do?"+ value={goal}+ onChange={(event) => setGoal(event.target.value)}+ className="w-full bg-white/[0.04] border border-white/[0.06] rounded-lg px-3 py-1.5 text-[12px] text-foreground placeholder-foreground/25 outline-none focus:border-primary/40 transition-all"+ />+ </div>++ <div className="px-4 py-2 border-b border-border/30 max-h-[120px] overflow-y-auto">+ {basket.items.length === 0 ? (+ <p className="text-[11px] text-foreground/25 py-1">+ Cite symbols, regions, flows or questions with “+ prompt” anywhere in Atlas.+ </p>+ ) : (+ basket.items.map((item) => (+ <div key={basketKey(item)} className="flex items-center gap-2 py-[3px]">+ <span className="text-[10px] uppercase tracking-wider text-foreground/25 w-14 shrink-0">+ {item.kind}+ </span>+ <span className="text-[11px] font-mono text-foreground/60 truncate flex-1">+ {itemLabel(item)}+ </span>+ <button+ onClick={() => basket.remove(basketKey(item))}+ className="text-foreground/20 hover:text-foreground/50 text-[12px] transition-colors"+ >+ ×+ </button>+ </div>+ ))+ )}+ </div>++ <pre className="flex-1 min-h-[120px] overflow-auto px-4 py-3 text-[10.5px] leading-relaxed font-mono text-foreground/70 whitespace-pre-wrap">+ {prompt}+ </pre>++ <div className="px-4 py-2.5 border-t border-border/40 flex justify-end">+ <button+ onClick={() => {+ navigator.clipboard?.writeText(prompt).then(() => setCopied(true));+ }}+ className="px-3 py-1.5 rounded-md bg-primary/20 text-primary text-[12px] font-medium hover:bg-primary/30 transition-colors"+ >+ {copied ? "Copied ✓" : "Copy prompt"}+ </button>+ </div>+ </div>+ );+}diff --git a/graph-ui/src/components/SymbolTab.tsx b/graph-ui/src/components/SymbolTab.tsxnew file mode 100644index 000000000..43728635a--- /dev/null+++ b/graph-ui/src/components/SymbolTab.tsx@@ -0,0 +1,349 @@+/* Symbol — one page per node, addressable by id or qualified name: what it+ * is (docstring, flags), where it lives (region, file, editor links), who+ * calls it and whom it calls (true totals, paged, confidence-ordered),+ * what tests it, what changes with it, and what nearly duplicates it. */+import { useEffect, useState } from "react";+import { ScrollArea } from "@/components/ui/scroll-area";+import { callTool } from "../api/rpc";+import {+ fetchSymbol,+ type ConnectionPage,+ type SymbolBundle,+ type SymbolRef,+} from "../lib/atlas";+import { AddToPromptButton } from "./PromptBasket";+import type { RepoInfo } from "../lib/types";++interface SymbolTabProps {+ project: string;+ symbolRef: { id?: number; qn?: string };+ onOpenSymbol: (ref: { id?: number; qn?: string }) => void;+ onOpenRegion: (regionId: number) => void;+}++const CONFIDENCE: Record<string, { label: string; tone: string }> = {+ CALLS: { label: "resolved", tone: "text-emerald-300/80 border-emerald-300/30" },+ CALL_REFERENCE: { label: "reference", tone: "text-sky-300/80 border-sky-300/30" },+ USAGE: { label: "unproven", tone: "text-amber-300/80 border-amber-300/30" },+ HTTP_CALLS: { label: "http", tone: "text-purple-300/80 border-purple-300/30" },+ ASYNC_CALLS: { label: "async", tone: "text-purple-300/80 border-purple-300/30" },+};++function ConnectionList({+ title,+ page,+ onLoadMore,+ onOpenSymbol,+}: {+ title: string;+ page: ConnectionPage;+ onLoadMore: () => void;+ onOpenSymbol: (ref: { id?: number; qn?: string }) => void;+}) {+ const shown = page.offset + page.items.length;+ return (+ <div className="bg-white/[0.02] border border-border/40 rounded-xl p-4">+ <div className="flex items-baseline gap-2 mb-2">+ <p className="text-[10px] uppercase tracking-widest text-foreground/30">{title}</p>+ <span className="text-[11px] tabular-nums text-foreground/40">+ {page.total.toLocaleString("en-US")}+ </span>+ <span className="text-[10px] text-foreground/25 ml-auto">+ {Object.entries(page.by_type)+ .map(([type, count]) => `${CONFIDENCE[type]?.label ?? type.toLowerCase()} ${count}`)+ .join(" · ")}+ </span>+ </div>+ <div className="space-y-px">+ {page.items.map((item, index) => (+ <button+ key={`${item.id}-${index}`}+ onClick={() => onOpenSymbol({ id: item.id })}+ className="flex items-center gap-2 w-full text-left px-2 py-[4px] rounded-md hover:bg-white/[0.04] transition-colors group"+ >+ <span+ className={`text-[9px] px-1 rounded border shrink-0 ${CONFIDENCE[item.type ?? ""]?.tone ?? "text-foreground/40 border-border/40"}`}+ >+ {CONFIDENCE[item.type ?? ""]?.label ?? item.type}+ </span>+ <span className="text-[11.5px] font-mono text-foreground/65 group-hover:text-primary truncate transition-colors">+ {item.name}+ </span>+ <span className="text-[10px] text-foreground/20 truncate ml-auto shrink-0 max-w-[45%]">+ {item.file_path}+ </span>+ </button>+ ))}+ {page.items.length === 0 && (+ <p className="text-[11px] text-foreground/25 px-2 py-2">None.</p>+ )}+ </div>+ {shown < page.total && (+ <button+ onClick={onLoadMore}+ className="mt-1.5 px-2 text-[10.5px] text-primary/70 hover:text-primary transition-colors"+ >+ Show more ({(page.total - shown).toLocaleString("en-US")} hidden)+ </button>+ )}+ </div>+ );+}++export function SymbolTab({ project, symbolRef, onOpenSymbol, onOpenRegion }: SymbolTabProps) {+ const [bundle, setBundle] = useState<SymbolBundle | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [limit, setLimit] = useState(50);+ const [code, setCode] = useState<string | null>(null);+ const [codeLoading, setCodeLoading] = useState(false);+ const [repoInfo, setRepoInfo] = useState<RepoInfo | null>(null);++ useEffect(() => {+ let cancelled = false;+ setBundle(null);+ setError(null);+ setCode(null);+ fetchSymbol(project, symbolRef, limit, 0)+ .then((payload) => {+ if (!cancelled) setBundle(payload);+ })+ .catch((err) => {+ if (!cancelled) setError(err instanceof Error ? err.message : "failed");+ });+ return () => {+ cancelled = true;+ };+ }, [project, symbolRef.id, symbolRef.qn, limit]);++ useEffect(() => {+ let cancelled = false;+ fetch(`/api/repo-info?project=${encodeURIComponent(project)}`)+ .then((res) => (res.ok ? res.json() : null))+ .then((data) => {+ if (!cancelled && data && !data.error) setRepoInfo(data as RepoInfo);+ })+ .catch(() => {});+ 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 (!bundle) {+ return (+ <div className="flex items-center justify-center h-full">+ <p className="text-white/30 text-sm">Loading symbol…</p>+ </div>+ );+ }++ const { node } = bundle;+ const lineSuffix = node.start_line+ ? `#L${node.start_line}${node.end_line && node.end_line !== node.start_line ? `-L${node.end_line}` : ""}`+ : "";+ const ghUrl =+ repoInfo?.blob_base && node.file_path+ ? `${repoInfo.blob_base}/${node.file_path.split("/").map(encodeURIComponent).join("/")}${lineSuffix}`+ : null;+ const editorUrl =+ repoInfo?.root_path && node.file_path+ ? `vscode://file/${repoInfo.root_path}/${node.file_path}${node.start_line ? `:${node.start_line}` : ""}`+ : null;++ const loadCode = async () => {+ if (!node.qualified_name) return;+ setCodeLoading(true);+ try {+ const result = await callTool<{ source?: string }>("get_code_snippet", {+ qualified_name: node.qualified_name,+ project,+ });+ setCode(result.source ?? "(source not available)");+ } catch (err) {+ setCode(err instanceof Error ? err.message : "failed to load code");+ } finally {+ setCodeLoading(false);+ }+ };++ return (+ <ScrollArea className="h-full">+ <div className="max-w-[1100px] mx-auto px-6 py-6">+ {/* Header */}+ <div className="mb-5">+ <div className="flex items-center gap-3 flex-wrap">+ <h2 className="text-[20px] font-semibold text-foreground/95 font-mono">+ {node.name}+ </h2>+ <span className="px-2 py-0.5 rounded-md text-[10px] font-medium bg-white/[0.06] text-foreground/60">+ {node.label}+ </span>+ {node.is_entry && (+ <span className="px-2 py-0.5 rounded-md text-[10px] bg-emerald-400/10 text-emerald-300/80">+ entry point+ </span>+ )}+ {node.is_test && (+ <span className="px-2 py-0.5 rounded-md text-[10px] bg-white/[0.06] text-foreground/50">+ test+ </span>+ )}+ {node.is_exported && (+ <span className="px-2 py-0.5 rounded-md text-[10px] bg-sky-400/10 text-sky-300/80">+ exported+ </span>+ )}+ <div className="ml-auto flex gap-2 items-center">+ <AddToPromptButton+ item={{+ kind: "symbol",+ id: node.id,+ name: node.name,+ qualified_name: node.qualified_name,+ file_path: node.file_path,+ start_line: node.start_line,+ end_line: node.end_line,+ }}+ />+ </div>+ </div>+ {node.qualified_name && (+ <p className="text-[11px] font-mono text-foreground/35 mt-1.5 break-all">+ {node.qualified_name}+ </p>+ )}+ <div className="flex items-center gap-3 mt-1.5 flex-wrap">+ {node.file_path && (+ <p className="text-[11px] font-mono text-foreground/45">+ {node.file_path}+ {node.start_line ? `:${node.start_line}` : ""}+ </p>+ )}+ {bundle.region && (+ <button+ onClick={() => onOpenRegion(bundle.region!.id)}+ className="text-[11px] text-primary/70 hover:text-primary transition-colors"+ >+ region: {bundle.region.name ?? bundle.region.id} →+ </button>+ )}+ {editorUrl && (+ <a href={editorUrl} className="text-[11px] text-foreground/40 hover:text-foreground/70 transition-colors">+ Open in editor ↗+ </a>+ )}+ {ghUrl && (+ <a+ href={ghUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-[11px] text-foreground/40 hover:text-foreground/70 transition-colors"+ >+ GitHub ↗+ </a>+ )}+ </div>+ {node.docstring && (+ <p className="text-[12.5px] text-foreground/60 mt-3 max-w-[75ch] leading-relaxed border-l-2 border-primary/30 pl-3">+ {node.docstring}+ </p>+ )}+ <div className="mt-3">+ <button+ onClick={code ? () => setCode(null) : loadCode}+ disabled={codeLoading || !node.qualified_name}+ className="px-2.5 py-1 rounded-md bg-primary/15 text-primary text-[11px] font-medium hover:bg-primary/25 transition-colors disabled:opacity-40"+ >+ {codeLoading ? "Loading…" : code ? "Hide code" : "Show code"}+ </button>+ {code && (+ <pre className="mt-2 max-h-[360px] overflow-auto rounded-md bg-black/40 border border-white/[0.06] p-3 text-[11px] leading-relaxed font-mono text-foreground/75 whitespace-pre">+ {code}+ </pre>+ )}+ </div>+ </div>++ {/* Connections */}+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">+ <ConnectionList+ title="Called by"+ page={bundle.callers}+ onLoadMore={() => setLimit((value) => value + 100)}+ onOpenSymbol={onOpenSymbol}+ />+ <ConnectionList+ title="Calls"+ page={bundle.callees}+ onLoadMore={() => setLimit((value) => value + 100)}+ onOpenSymbol={onOpenSymbol}+ />+ </div>++ <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">+ <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">+ Tested by+ </p>+ {(bundle.tests ?? []).map((test: SymbolRef) => (+ <button+ key={test.id}+ onClick={() => onOpenSymbol({ id: test.id })}+ className="block w-full text-left text-[11px] font-mono text-foreground/60 hover:text-primary py-[3px] truncate transition-colors"+ >+ {test.name}+ </button>+ ))}+ {(bundle.tests ?? []).length === 0 && (+ <p className="text-[11px] text-amber-300/50">No TESTS edges reach this symbol.</p>+ )}+ </div>++ <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">+ Changes together with+ </p>+ {(bundle.co_change ?? []).map((partner) => (+ <p key={partner.file_path} className="text-[11px] font-mono text-foreground/55 py-[3px] truncate">+ {partner.file_path}+ {partner.score !== undefined && (+ <span className="text-foreground/25"> · {partner.score.toFixed(2)}</span>+ )}+ </p>+ ))}+ {(bundle.co_change ?? []).length === 0 && (+ <p className="text-[11px] text-foreground/25">No co-change history.</p>+ )}+ </div>++ <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">+ Near-clones+ </p>+ {(bundle.similar ?? []).map((clone) => (+ <button+ key={clone.id}+ onClick={() => onOpenSymbol({ id: clone.id })}+ className="block w-full text-left text-[11px] font-mono text-foreground/60 hover:text-primary py-[3px] truncate transition-colors"+ >+ {clone.name}+ {clone.score !== undefined && (+ <span className="text-foreground/25"> · {clone.score.toFixed(2)}</span>+ )}+ </button>+ ))}+ {(bundle.similar ?? []).length === 0 && (+ <p className="text-[11px] text-foreground/25">No near-clones.</p>+ )}+ </div>+ </div>+ </div>+ </ScrollArea>+ );+}diff --git a/graph-ui/src/lib/atlas.test.ts b/graph-ui/src/lib/atlas.test.tsnew file mode 100644index 000000000..2aa33f18c--- /dev/null+++ b/graph-ui/src/lib/atlas.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from "vitest";+import { archRows } from "./atlas";+import { surprisingCouplings, suggestedQuestions } from "./firstread";+import { squarify } from "./treemap";+import { composePrompt } from "./composer";+import type { Region, RegionsPayload } from "./types";++function region(partial: Partial<Region> & { id: number; name: string }): Region {+ return {+ files: 4,+ members: 100,+ cohesion: 0.5,+ top_nodes: [],+ x: 0,+ y: 0,+ z: 0,+ size: 20,+ color: "#123456",+ ...partial,+ };+}++describe("archRows", () => {+ it("decodes {cols, rows} sections into row objects", () => {+ const arch = {+ hotspots: { cols: ["qn", "fan_in"], rows: [["a.b.c", 42], ["d.e.f", 7]] },+ project: "demo",+ };+ expect(archRows(arch, "hotspots")).toEqual([+ { qn: "a.b.c", fan_in: 42 },+ { qn: "d.e.f", fan_in: 7 },+ ]);+ expect(archRows(arch, "absent")).toEqual([]);+ expect(archRows(null, "hotspots")).toEqual([]);+ });+});++describe("first read", () => {+ const payload: RegionsPayload = {+ level: "regions",+ method: "leiden+folders",+ total_nodes: 20000,+ unmapped_nodes: 0,+ regions: [+ region({ id: 0, name: "src/pipeline", cohesion: 0.8, members: 900 }),+ region({ id: 1, name: "tests/e2e", cohesion: 0.7, members: 400 }),+ region({ id: 2, name: "src/store", cohesion: 0.15, members: 600 }),+ region({ id: 3, name: "misc", members: 50 }),+ ],+ edges: [+ { source: 0, target: 1, weight: 120 },+ { source: 0, target: 2, weight: 40 },+ { source: 3, target: 0, weight: 999 },+ ],+ };++ it("ranks cross-area couplings with reasons and ignores misc", () => {+ const out = surprisingCouplings(payload, 5);+ expect(out).toHaveLength(2);+ /* src→tests crosses top-level areas and is heavier. */+ expect(out[0].source.name).toBe("src/pipeline");+ expect(out[0].target.name).toBe("tests/e2e");+ expect(out[0].reasons.some((reason) => reason.includes("different top-level"))).toBe(true);+ /* src/store's looseness is called out on the second coupling. */+ expect(out[1].reasons.some((reason) => reason.includes("cohesion 0.15"))).toBe(true);+ });++ it("asks split/dead/certainty questions with a why", () => {+ const questions = suggestedQuestions(payload, { deadCount: 87, unresolvedShare: 0.4 });+ const texts = questions.map((question) => question.question);+ expect(texts.some((text) => text.includes("Should src/store be split"))).toBe(true);+ expect(texts.some((text) => text.includes("87 functions with no callers"))).toBe(true);+ for (const question of questions) expect(question.why.length).toBeGreaterThan(0);+ });+});++describe("squarify", () => {+ it("tiles the full rectangle with area-proportional cells", () => {+ const rects = squarify(+ [+ { id: "a", value: 6 },+ { id: "b", value: 3 },+ { id: "c", value: 1 },+ ],+ 0,+ 0,+ 100,+ 50,+ );+ expect(rects).toHaveLength(3);+ const area = (id: string) => {+ const rect = rects.find((r) => r.id === id)!;+ return rect.w * rect.h;+ };+ expect(area("a")).toBeCloseTo(3000, 0);+ expect(area("b")).toBeCloseTo(1500, 0);+ expect(area("c")).toBeCloseTo(500, 0);+ const total = rects.reduce((a, rect) => a + rect.w * rect.h, 0);+ expect(total).toBeCloseTo(5000, 0);+ for (const rect of rects) {+ expect(rect.x).toBeGreaterThanOrEqual(0);+ expect(rect.y).toBeGreaterThanOrEqual(0);+ expect(rect.x + rect.w).toBeLessThanOrEqual(100.001);+ expect(rect.y + rect.h).toBeLessThanOrEqual(50.001);+ }+ });++ it("handles empty and zero-value input", () => {+ expect(squarify([], 0, 0, 10, 10)).toEqual([]);+ expect(squarify([{ id: "a", value: 0 }], 0, 0, 10, 10)).toEqual([]);+ });+});++describe("composePrompt", () => {+ it("cites exact identifiers and the MCP calls that reproduce context", () => {+ const prompt = composePrompt("demo", "Refactor the store locking.", [+ {+ kind: "symbol",+ id: 7,+ name: "cbm_store_close",+ qualified_name: "demo.src.store.cbm_store_close",+ file_path: "src/store/store.c",+ start_line: 100,+ end_line: 140,+ },+ { kind: "region", id: 0, name: "src/store", members: 600, why: "call community" },+ { kind: "question", question: "Should src/store be split?", why: "cohesion 0.15" },+ ]);+ expect(prompt).toContain("Refactor the store locking.");+ expect(prompt).toContain("demo.src.store.cbm_store_close — src/store/store.c:100-140");+ expect(prompt).toContain('get_code_snippet(qualified_name: "demo.src.store.cbm_store_close"');+ expect(prompt).toContain('trace_path(qualified_name: "demo.src.store.cbm_store_close"');+ expect(prompt).toContain("Should src/store be split?");+ expect(prompt).toContain("USAGE edges mean the graph could not prove");+ });+});diff --git a/graph-ui/src/lib/atlas.ts b/graph-ui/src/lib/atlas.tsnew file mode 100644index 000000000..1754e4c4a--- /dev/null+++ b/graph-ui/src/lib/atlas.ts@@ -0,0 +1,237 @@+/* CBM Atlas data layer: the /api services and the read-only /rpc tools the+ * Atlas screens consume. */+import { callTool } from "../api/rpc";++/* ── /api/tree ──────────────────────────────────────────────── */++export interface TreeChild {+ name: string;+ path: string;+ kind: "dir" | "file";+ symbols: number;+ files: number;+ missed?: number;+ region?: number;+}++export interface TreePayload {+ path: string;+ files: number;+ symbols: number;+ children_dropped?: number;+ children: TreeChild[];+}++async function getJson<T>(url: string): Promise<T> {+ const res = await fetch(url);+ if (!res.ok) {+ const body = await res.json().catch(() => ({ error: res.statusText }));+ throw new Error(body.error ?? `HTTP ${res.status}`);+ }+ return res.json();+}++export function fetchTree(project: string, path: string): Promise<TreePayload> {+ const params = new URLSearchParams({ project, path });+ return getJson(`/api/tree?${params}`);+}++/* ── /api/symbol ────────────────────────────────────────────── */++export interface SymbolRef {+ id: number;+ name: string;+ label?: string;+ file_path?: string;+ start_line?: number;+ qualified_name?: string;+ type?: string;+}++export interface ConnectionPage {+ total: number;+ by_type: Record<string, number>;+ limit: number;+ offset: number;+ items: SymbolRef[];+}++export interface SymbolBundle {+ node: {+ id: number;+ label: string;+ name: string;+ qualified_name?: string;+ file_path?: string;+ start_line?: number;+ end_line?: number;+ docstring?: string;+ is_entry?: boolean;+ is_test?: boolean;+ is_exported?: boolean;+ };+ region?: { id: number; name?: string };+ callers: ConnectionPage;+ callees: ConnectionPage;+ tests?: SymbolRef[];+ co_change?: { file_path: string; score?: number }[];+ similar?: { id: number; name: string; file_path?: string; score?: number }[];+}++export function fetchSymbol(+ project: string,+ ref: { id?: number; qn?: string },+ limit = 50,+ offset = 0,+): Promise<SymbolBundle> {+ const params = new URLSearchParams({ project, limit: String(limit), offset: String(offset) });+ if (ref.id !== undefined) params.set("id", String(ref.id));+ else if (ref.qn) params.set("qn", ref.qn);+ return getJson(`/api/symbol?${params}`);+}++/* ── /api/flows ─────────────────────────────────────────────── */++export interface FlowSummary {+ id: number;+ label: string;+ entry: SymbolRef;+ terminal: SymbolRef;+ steps: number;+ sink_terminated: boolean;+ cross_region: boolean;+ steps_capped?: number;+}++export interface FlowsPayload {+ callable_total: number;+ candidates_dropped: number;+ flows: FlowSummary[];+}++export interface FlowStep {+ id: number;+ name: string;+ file_path?: string;+ depth: number;+ parent: number;+}++export interface FlowDetail {+ id: number;+ entry: SymbolRef;+ terminal: SymbolRef;+ sink_terminated: boolean;+ cross_region: boolean;+ steps_capped?: number;+ steps: FlowStep[];+}++export function fetchFlows(project: string): Promise<FlowsPayload> {+ return getJson(`/api/flows?${new URLSearchParams({ project })}`);+}++export function fetchFlow(project: string, id: number): Promise<FlowDetail> {+ return getJson(`/api/flow?${new URLSearchParams({ project, id: String(id) })}`);+}++/* ── get_architecture (format:"json" → {cols, rows} sections) ── */++export interface ArchSection {+ cols: string[];+ rows: (string | number | null)[][];+}++export type ArchitectureJson = Record<string, ArchSection | string | number>;++/* Decode one {cols, rows} section into row objects. Absent → []. */+export function archRows<T = Record<string, string | number | null>>(+ arch: ArchitectureJson | null,+ section: string,+): T[] {+ const s = arch?.[section];+ if (!s || typeof s !== "object" || !("cols" in s)) return [];+ const { cols, rows } = s as ArchSection;+ return rows.map((row) => {+ const obj: Record<string, string | number | null> = {};+ cols.forEach((col, i) => {+ obj[col] = row[i] ?? null;+ });+ return obj as T;+ });+}++export function fetchArchitecture(project: string): Promise<ArchitectureJson> {+ return callTool<ArchitectureJson>("get_architecture", {+ project,+ format: "json",+ aspects: ["overview"],+ });+}++/* ── detect_changes (format:"json") ─────────────────────────── */++export function fetchChanges(project: string): Promise<ArchitectureJson> {+ return callTool<ArchitectureJson>("detect_changes", {+ project,+ format: "json",+ risk_labels: true,+ });+}++/* ── search_graph (format:"json") ───────────────────────────────+ * Shape: {total, count, cols, groups:[{qn_prefix, file, rows}], has_more}.+ * The first row column is the qualified-name SUFFIX under qn_prefix. */++export interface SearchRow {+ qualified_name: string;+ name: string;+ label: string;+ lines?: string;+ fan_in: number;+ fan_out: number;+ file?: string;+}++interface SearchGroupsJson {+ total?: number;+ count?: number;+ groups?: {+ qn_prefix?: string;+ file?: string;+ rows: (string | number | null)[][];+ }[];+ has_more?: boolean;+}++export function decodeSearchGroups(payload: SearchGroupsJson): SearchRow[] {+ const out: SearchRow[] = [];+ for (const group of payload.groups ?? []) {+ for (const row of group.rows ?? []) {+ const suffix = String(row[0] ?? "");+ const qualified = group.qn_prefix ? `${group.qn_prefix}.${suffix}` : suffix;+ out.push({+ qualified_name: qualified,+ name: suffix.split(".").pop() ?? suffix,+ label: String(row[1] ?? ""),+ lines: row[2] ? String(row[2]) : undefined,+ fan_in: Number(row[3] ?? 0),+ fan_out: Number(row[4] ?? 0),+ file: group.file,+ });+ }+ }+ return out;+}++export async function searchGraph(+ project: string,+ args: Record<string, unknown>,+): Promise<{ rows: SearchRow[]; total: number }> {+ const payload = await callTool<SearchGroupsJson>("search_graph", {+ project,+ format: "json",+ ...args,+ });+ return { rows: decodeSearchGroups(payload), total: payload.total ?? 0 };+}diff --git a/graph-ui/src/lib/composer.ts b/graph-ui/src/lib/composer.tsnew file mode 100644index 000000000..d41b91564--- /dev/null+++ b/graph-ui/src/lib/composer.ts@@ -0,0 +1,90 @@+/* The prompt composer: the bridge from what the human learned to what the+ * agent is told. A basket of cited entities becomes a prompt that names+ * exact identifiers and the MCP calls that reproduce the context. */++export type BasketItem =+ | { kind: "symbol"; id: number; name: string; qualified_name?: string; file_path?: string; start_line?: number; end_line?: number }+ | { kind: "region"; id: number; name: string; members: number; why?: string }+ | { kind: "flow"; id: number; label: string; steps: number }+ | { kind: "question"; question: string; why: string };++export function basketKey(item: BasketItem): string {+ switch (item.kind) {+ case "symbol":+ return `symbol:${item.id}`;+ case "region":+ return `region:${item.id}`;+ case "flow":+ return `flow:${item.id}`;+ case "question":+ return `question:${item.question}`;+ }+}++/* Render the basket + the human's goal into a prompt for a coding agent.+ * Structure: goal → exact citations → how to reproduce the context via MCP+ * → honesty notes. Deterministic; no timestamps. */+export function composePrompt(project: string, goal: string, items: BasketItem[]): string {+ const lines: string[] = [];+ lines.push(goal.trim() || "Help me with the code cited below.");+ lines.push("");+ lines.push(`Project (codebase-memory-mcp index): ${project}`);++ const symbols = items.filter((item) => item.kind === "symbol");+ const regions = items.filter((item) => item.kind === "region");+ const flows = items.filter((item) => item.kind === "flow");+ const questions = items.filter((item) => item.kind === "question");++ if (symbols.length > 0) {+ lines.push("");+ lines.push("Symbols involved (exact identifiers):");+ for (const s of symbols) {+ const where =+ s.file_path && s.start_line+ ? ` — ${s.file_path}:${s.start_line}${s.end_line && s.end_line !== s.start_line ? `-${s.end_line}` : ""}`+ : s.file_path+ ? ` — ${s.file_path}`+ : "";+ lines.push(`- ${s.qualified_name ?? s.name}${where}`);+ }+ }+ if (regions.length > 0) {+ lines.push("");+ lines.push("Modules (call-community regions from the graph):");+ for (const r of regions) {+ lines.push(+ `- ${r.name} (${r.members.toLocaleString("en-US")} symbols${r.why ? `; ${r.why}` : ""})`,+ );+ }+ }+ if (flows.length > 0) {+ lines.push("");+ lines.push("Flows (entry → terminal call journeys):");+ for (const f of flows) lines.push(`- ${f.label} (${f.steps} steps)`);+ }+ if (questions.length > 0) {+ lines.push("");+ lines.push("Open questions:");+ for (const q of questions) lines.push(`- ${q.question} (${q.why})`);+ }++ lines.push("");+ lines.push("To reproduce this context with the codebase-memory-mcp tools:");+ for (const s of symbols.slice(0, 5)) {+ if (s.qualified_name) {+ lines.push(+ `- get_code_snippet(qualified_name: "${s.qualified_name}", project: "${project}")`,+ );+ lines.push(+ `- trace_path(qualified_name: "${s.qualified_name}", project: "${project}", direction: "inbound")`,+ );+ }+ }+ lines.push(`- get_architecture(project: "${project}") for the module map`);+ lines.push("");+ lines.push(+ "Note: CALLS edges are resolved calls; USAGE edges mean the graph could not " ++ "prove a single target — verify before relying on them.",+ );+ return lines.join("\n");+}diff --git a/graph-ui/src/lib/firstread.ts b/graph-ui/src/lib/firstread.tsnew file mode 100644index 000000000..40973825e--- /dev/null+++ b/graph-ui/src/lib/firstread.ts@@ -0,0 +1,115 @@+/* The "first read": deterministic teaching artifacts computed from data the+ * graph already holds — every insight carries the reason it is interesting.+ * No model, no scores without provenance. */+import type { Region, RegionsPayload } from "./types";+import { disambiguateRegionNames } from "./regions";++export interface SurprisingCoupling {+ source: Region;+ target: Region;+ weight: number;+ reasons: string[];+}++/* Cross-region couplings ranked by an explained score: heavier links, links+ * that cross top-level directories, and links touching a low-cohesion region+ * rank higher. `misc` never surprises anyone. */+export function surprisingCouplings(+ payload: RegionsPayload,+ limit = 5,+): SurprisingCoupling[] {+ const regions = disambiguateRegionNames(payload.regions);+ const byId = new Map(regions.map((region) => [region.id, region]));+ const top = (name: string) => name.split("/")[0] ?? name;+ const scored: (SurprisingCoupling & { score: number })[] = [];+ for (const edge of payload.edges) {+ const source = byId.get(edge.source);+ const target = byId.get(edge.target);+ if (!source || !target) continue;+ if (source.name === "misc" || target.name === "misc") continue;+ const reasons: string[] = [];+ let score = Math.log2(1 + edge.weight);+ reasons.push(`${edge.weight.toLocaleString("en-US")} edges cross the boundary`);+ if (top(source.name) !== top(target.name)) {+ score += 2;+ reasons.push(+ `links ${top(source.name)}/ to ${top(target.name)}/ — different top-level areas`,+ );+ }+ if (source.cohesion < 0.3 || target.cohesion < 0.3) {+ score += 1;+ const loose = source.cohesion < target.cohesion ? source : target;+ reasons.push(+ `${loose.name} holds together loosely (cohesion ${loose.cohesion.toFixed(2)})`,+ );+ }+ scored.push({ source, target, weight: edge.weight, reasons, score });+ }+ scored.sort(+ (a, b) => b.score - a.score || b.weight - a.weight || a.source.id - b.source.id,+ );+ return scored.slice(0, limit).map(({ score: _score, ...rest }) => rest);+}++export interface SuggestedQuestion {+ question: string;+ why: string;+ /* Seed for the prompt composer: the entities the question is about. */+ about: string[];+}++export interface FirstReadStats {+ deadCount?: number;+ unresolvedShare?: number; /* USAGE / (CALLS+CALL_REFERENCE+USAGE), 0..1 */+}++/* Question templates keyed to structural signals — each one is a prompt+ * starter the human can hand to their agent. */+export function suggestedQuestions(+ payload: RegionsPayload,+ stats: FirstReadStats = {},+ limit = 5,+): SuggestedQuestion[] {+ const regions = disambiguateRegionNames(payload.regions).filter(+ (region) => region.name !== "misc",+ );+ const questions: SuggestedQuestion[] = [];++ const couplings = surprisingCouplings(payload, 2);+ for (const coupling of couplings) {+ questions.push({+ question: `Why does ${coupling.source.name} depend on ${coupling.target.name}?`,+ why: coupling.reasons.join("; "),+ about: [coupling.source.name, coupling.target.name],+ });+ }++ const loose = [...regions]+ .filter((region) => region.members >= 50 && region.cohesion > 0 && region.cohesion < 0.25)+ .sort((a, b) => a.cohesion - b.cohesion)[0];+ if (loose) {+ questions.push({+ question: `Should ${loose.name} be split into smaller modules?`,+ why: `only ${(loose.cohesion * 100).toFixed(0)}% of its edges stay inside the region (${loose.members.toLocaleString("en-US")} symbols)`,+ about: [loose.name],+ });+ }++ if (stats.deadCount && stats.deadCount > 0) {+ questions.push({+ question: `Are the ${stats.deadCount.toLocaleString("en-US")} functions with no callers safe to delete?`,+ why: "zero CALLS and zero USAGE reach them, excluding entry points and tests",+ about: ["dead code"],+ });+ }++ if (stats.unresolvedShare !== undefined && stats.unresolvedShare > 0.3) {+ questions.push({+ question: "Which call sites does the graph fail to resolve, and why?",+ why: `${(stats.unresolvedShare * 100).toFixed(0)}% of call-ish edges are USAGE (no proven single target)`,+ about: ["resolution certainty"],+ });+ }++ return questions.slice(0, limit);+}diff --git a/graph-ui/src/lib/treemap.ts b/graph-ui/src/lib/treemap.tsnew file mode 100644index 000000000..a3a7bb282--- /dev/null+++ b/graph-ui/src/lib/treemap.ts@@ -0,0 +1,92 @@+/* Squarified treemap layout (Bruls, Huizing & van Wijk 2000) — in-house so+ * the Modules screen needs no new dependency. Deterministic: input order is+ * preserved inside rows; items should arrive value-sorted descending. */++export interface TreemapItem {+ id: string;+ value: number;+}++export interface TreemapRect {+ id: string;+ x: number;+ y: number;+ w: number;+ h: number;+}++/* Worst aspect ratio a row would have if `row` (+lengths) shared `side`. */+function worst(row: number[], side: number, total: number): number {+ if (row.length === 0 || total <= 0) return Infinity;+ const sum = row.reduce((a, b) => a + b, 0);+ const max = Math.max(...row);+ const min = Math.min(...row);+ const s2 = sum * sum;+ const sideSq = side * side;+ return Math.max((sideSq * max) / s2, s2 / (sideSq * min));+}++export function squarify(+ items: TreemapItem[],+ x: number,+ y: number,+ w: number,+ h: number,+): TreemapRect[] {+ const positive = items.filter((item) => item.value > 0);+ const total = positive.reduce((a, item) => a + item.value, 0);+ if (positive.length === 0 || total <= 0 || w <= 0 || h <= 0) return [];+ /* Scale values to areas within the rect. */+ const scale = (w * h) / total;+ let queue = positive.map((item) => ({ id: item.id, area: item.value * scale }));+ const out: TreemapRect[] = [];+ let cx = x;+ let cy = y;+ let cw = w;+ let ch = h;++ while (queue.length > 0) {+ const side = Math.min(cw, ch);+ const row: typeof queue = [];+ let rowAreas: number[] = [];+ /* Grow the row while the worst aspect ratio improves. */+ while (queue.length > 0) {+ const candidate = [...rowAreas, queue[0].area];+ if (+ rowAreas.length === 0 ||+ worst(candidate, side, 1) <= worst(rowAreas, side, 1)+ ) {+ row.push(queue[0]);+ rowAreas = candidate;+ queue = queue.slice(1);+ } else {+ break;+ }+ }+ const rowArea = rowAreas.reduce((a, b) => a + b, 0);+ if (cw >= ch) {+ /* Vertical strip on the left. */+ const stripW = rowArea / ch;+ let oy = cy;+ for (const item of row) {+ const cellH = item.area / stripW;+ out.push({ id: item.id, x: cx, y: oy, w: stripW, h: cellH });+ oy += cellH;+ }+ cx += stripW;+ cw -= stripW;+ } else {+ /* Horizontal strip on top. */+ const stripH = rowArea / cw;+ let ox = cx;+ for (const item of row) {+ const cellW = item.area / stripH;+ out.push({ id: item.id, x: ox, y: cy, w: cellW, h: stripH });+ ox += cellW;+ }+ cy += stripH;+ ch -= stripH;+ }+ }+ return out;+}diff --git a/graph-ui/src/lib/types.ts b/graph-ui/src/lib/types.tsindex 7cd37fe11..cf4317d7f 100644--- a/graph-ui/src/lib/types.ts+++ b/graph-ui/src/lib/types.ts@@ -113,7 +113,15 @@ export interface SchemaInfo {total_edges: number;}-export type TabId = "graph" | "stats" | "control";+export type TabId =+ | "overview"+ | "modules"+ | "graph"+ | "flows"+ | "changes"+ | "symbol"+ | "stats"+ | "control";export interface ProcessInfo {pid: number;diff --git a/graph-ui/tsconfig.tsbuildinfo b/graph-ui/tsconfig.tsbuildinfoindex 1207dc1dc..d1716ee91 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/controltab.tsx","./src/components/displaysettingsmenu.tsx","./src/components/edgelines.tsx","./src/components/errorboundary.tsx","./src/components/filterpanel.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/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/projectcard.tsx","./src/components/regionpanel.tsx","./src/components/resizehandle.tsx","./src/components/sidebar.tsx","./src/components/statstab.test.tsx","./src/components/statstab.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/colors.ts","./src/lib/density.test.ts","./src/lib/density.ts","./src/lib/i18n.test.ts","./src/lib/i18n.ts","./src/lib/regions.test.ts","./src/lib/regions.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/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/http_server.c b/src/ui/http_server.cindex 1b473ab4a..428d73dff 100644--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@ -2138,7 +2138,7 @@ static void dispatch_request(cbm_http_server_t *srv, cbm_http_conn_t *c,}/* GET /api/flow → one CBM Atlas flow */- if (is_get && cbm_http_path_match(req->path, "/api/flow?*")) {+ if (is_get && cbm_http_path_match(req->path, "/api/flow")) {handle_atlas_flow(c, req);return;}diff --git a/tests/test_httpd.c b/tests/test_httpd.cindex 18a1a5b00..f1df83347 100644--- a/tests/test_httpd.c+++ b/tests/test_httpd.c@@ -1184,6 +1184,26 @@ TEST(ui_server_rpc_allows_only_ui_read_tools) {PASS();}+TEST(ui_server_atlas_routes_are_wired) {+ th_server_t ts;+ ASSERT_EQ(th_server_start(&ts), 0);+ /* A wired route with a missing ?project answers 400; an unwired path+ * 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"};+ char req[256];+ char resp[4096];+ for (size_t i = 0; i < sizeof(routes) / sizeof(routes[0]); i++) {+ snprintf(req, sizeof(req), "GET %s HTTP/1.1\r\n\r\n", routes[i]);+ int n = th_http(cbm_http_server_port(ts.srv), req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 400);+ }+ th_server_stop(&ts);+ PASS();+}+TEST(ui_server_oversized_body_rejected) {th_server_t ts;ASSERT_EQ(th_server_start(&ts), 0);@@ -2340,6 +2360,7 @@ SUITE(httpd) {RUN_TEST(ui_server_rejects_foreign_and_null_origins);RUN_TEST(ui_server_mutations_require_json_content_type);RUN_TEST(ui_server_rpc_allows_only_ui_read_tools);+ RUN_TEST(ui_server_atlas_routes_are_wired);RUN_TEST(ui_server_oversized_body_rejected);RUN_TEST(ui_server_encoded_slash_not_routed);RUN_TEST(ui_server_nul_in_target_rejected);