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
Merge origin/main into feat/atlas-r1
Martin Vogelda7235ab39b9
diff --cc README.mdindex 01c4d8c44,b41939a8f..7d5ffb6cf--- a/README.md+++ b/README.md@@@ -32,10 -32,10 +32,10 @@@ High-quality parsing through [tree-sitt- **Extreme indexing speed** — Linux kernel (28M LOC, 75K files) in 3 minutes. RAM-first pipeline: LZ4 compression, in-memory SQLite, fused Aho-Corasick pattern matching. Memory released after indexing.- **Plug and play** — native executable plus authenticated release-owned assets for macOS (arm64/amd64), Linux (arm64/amd64), and Windows (amd64). The native install needs no Docker, language runtime, or API keys. Download → `install` → restart agent → done.- - **158 languages** — vendored tree-sitter grammars compiled into the binary. Nothing to install, nothing that breaks.+ - **162 languages** — vendored tree-sitter grammars compiled into the binary. Nothing to install, nothing that breaks.- **120x fewer tokens** — 5 structural queries: ~3,400 tokens vs ~412,000 via file-by-file search. One graph query replaces dozens of grep/read cycles.- - **43 supported automatic/conditional client surfaces** — `install` configures detected clients and safely activates conditional clients only when their documented platform, marker, or explicit existing config path is present. See [Multi-Agent Support](#multi-agent-support) for the complete matrix and manual/UI-only boundaries.+ - **45 supported automatic/conditional client surfaces** — `install` configures detected clients and safely activates conditional clients only when their documented platform, marker, or explicit existing config path is present. See [Multi-Agent Support](#multi-agent-support) for the complete matrix and manual/UI-only boundaries.-- **Built-in graph visualization** — 3D interactive UI at `localhost:9749`, served from the binary itself.+- **CBM Atlas** — the built-in human interface at `localhost:9749`: overview, modules treemap, region-level 3D galaxy, call flows, change impact, symbol pages and a prompt composer, served from the binary itself.- **Infrastructure-as-code indexing** — Dockerfiles, Kubernetes manifests, and Kustomize overlays indexed as graph nodes with cross-references. `Resource` nodes for K8s kinds, `Module` nodes for Kustomize overlays with `IMPORTS` edges to referenced resources.- **15 MCP tools** — search, trace, architecture, impact analysis, targeted index-coverage checks, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.diff --cc graph-ui/src/App.tsxindex cc3e4ee7b,a0d84b0b6..617ea49dd--- a/graph-ui/src/App.tsx+++ b/graph-ui/src/App.tsx@@@ -75,146 -33,69 +75,172 @@@ function routeUrl(route: RouteState): sexport function App() {const t = useUiMessages();const [route, setRoute] = useState<RouteState>(readRoute);- const [version, setVersion] = useState<string | null>(null);+ const [commandOpen, setCommandOpen] = useState(false);+ /* The metric wiki: any dotted-underline term opens its entry here. */+ const [wikiSlug, setWikiSlug] = useState<string | null>(null);+ /* The galaxy keeps its WebGL context and layout across tab switches:+ * mounted once visited, hidden with `invisible` (never display:none, which+ * would zero the canvas), frameloop paused while hidden. */+ const [graphVisited, setGraphVisited] = useState(false);+ useEffect(() => {+ if (route.tab === "graph") setGraphVisited(true);+ }, [route.tab]);const { tab: activeTab, project: selectedProject } = route;++ const [version, setVersion] = useState<string | null>(null);+++ useEffect(() => {+ let cancelled = false;+ void fetch("/api/ui-config")+ .then((response) => (response.ok ? response.json() : null))+ .then((config) => {+ if (!cancelled && typeof config?.version === "string" && config.version) {+ setVersion(config.version);+ }+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, []);++ /* 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));+ 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) => {- const url = routeUrl(tab, project);- const current = `${window.location.pathname}${window.location.search}${window.location.hash}`;- if (url === current) return;- window.history.pushState(null, "", url);- setRoute({ tab, project });+ /* #wiki=<slug> deep link: wiki entries are addressable by URL (the doc_url+ * target), opening the panel over whatever view the rest of the URL names. */+ useEffect(() => {+ const openFromHash = () => {+ const match = window.location.hash.match(/wiki=([a-z][a-z-]*)/);+ if (match && wikiEntry(match[1])) setWikiSlug(match[1]);+ };+ openFromHash();+ window.addEventListener("hashchange", openFromHash);+ return () => window.removeEventListener("hashchange", openFromHash);+ }, []);++ /* ⌘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 tabs: { id: TabId; label: string }[] = [+ 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) 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],+ );++ /* Project-scoped views only — they render once a project is chosen.+ * App-level destinations (Projects, Control) live on the right instead of+ * being mixed into this row as dead buttons. */+ const projectTabs: { id: TabId; label: string }[] = [+ { id: "overview", label: t.tabs.overview },+ { id: "modules", label: t.tabs.modules },{ id: "graph", label: t.tabs.graph },- { id: "stats", label: t.tabs.projects },- { id: "control", label: t.tabs.control },+ { id: "flows", label: t.tabs.flows },+ { id: "changes", label: t.tabs.changes },+ { id: "dashboard", label: t.tabs.dashboard },];+ 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">- Codebase Memory- </span>- {version && (- <span- className="translate-y-px text-[10px] font-mono text-foreground/30"- title="Server version"- >- {version.startsWith("v") ? version : `v${version}`}+ <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-card/80 backdrop-blur-md shrink-0">+ <div className="flex items-center gap-4 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>++ {version && (++ <span++ className="translate-y-px text-[10px] font-mono text-foreground/30"++ title="Server version"++ >++ {version.startsWith("v") ? version : `v${version}`}++ </span>++ )}+ </div>++ {/* Context first: which project is everything below about? */}+ <ProjectSwitcher+ selected={selectedProject}+ labels={t.switcher}+ allProjectsLabel={t.tabs.projects}+ onSelect={(project) => navigate({ tab: "overview", project })}+ onAllProjects={() => navigate({ tab: "stats", project: null })}+ />++ {selectedProject && (+ <>+ <div className="w-px h-5 bg-border/50 shrink-0" />+ <nav className="flex items-center gap-0.5 overflow-x-auto">+ {projectTabs.map((tab) => (+ <button+ key={tab.id}+ onClick={() => navigate({ tab: tab.id, project: selectedProject })}+ className={`px-3 py-1 rounded-md text-[12px] font-medium transition-all whitespace-nowrap ${+ activeTab === tab.id+ ? "bg-primary/15 text-primary"+ : "text-muted-foreground hover:text-foreground hover:bg-surface-3"+ }`}+ >+ {tab.label}+ </button>+ ))}+ </nav>+ </>)}</div>diff --cc graph-ui/src/components/GraphTab.tsxindex 75d19aa22,2f3a17e14..7f430386f--- a/graph-ui/src/components/GraphTab.tsx+++ b/graph-ui/src/components/GraphTab.tsx@@@ -378,60 -257,6 +378,44 @@@ export function GraphTab(};}, [project]);+ /* Search scent: a query is answerable from the coarsest view — matched+ * regions brighten and carry hit counts before any drill. */+ const [scentQuery, setScentQuery] = useState("");+ const [scent, setScent] = useState<{+ total: number;+ unmapped: number;+ counts: Map<number, number>;+ } | null>(null);+ useEffect(() => {+ setScentQuery("");+ setScent(null);+ }, [project]);+ useEffect(() => {+ const q = scentQuery.trim();+ if (!project || q.length < 2) {+ setScent(null);+ return;+ }+ let cancelled = false;+ const timer = setTimeout(async () => {+ try {+ const payload = await fetchScent(project, q);+ if (cancelled) return;+ setScent({+ total: payload.total,+ unmapped: payload.unmapped,+ counts: new Map(payload.regions.map((row) => [row.region, row.count])),+ });+ } catch {+ if (!cancelled) setScent(null);+ }+ }, 300);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [project, scentQuery]);+- const handleSelectPath = useCallback(- (path: string, nodeIds: Set<number>) => {- if (!filteredData || !path || nodeIds.size === 0) {- setHighlightedIds(null);- setSelectedPath(null);- setCameraTarget(null);- return;- }- setSelectedPath(path);- setHighlightedIds(nodeIds);- setSelectedNode(null); /* #1197: never leave a stale node in the panel */- setCameraTarget(computeCameraTarget(filteredData.nodes, nodeIds));- },- [filteredData],- );-const handleNodeClick = useCallback((node: GraphNode) => {if (!filteredData) return;diff --cc graph-ui/src/hooks/useProjects.test.tsxindex 000000000,10d36a97c..3e581eab6mode 000000,100644..100644--- a/graph-ui/src/hooks/useProjects.test.tsx+++ b/graph-ui/src/hooks/useProjects.test.tsx@@@ -1,0 -1,86 +1,90 @@@+ /* @vitest-environment jsdom */+ import { renderHook, waitFor } from "@testing-library/react";+ import { beforeEach, describe, expect, it, vi } from "vitest";+ import { useProjects } from "./useProjects";++ const callToolMock = vi.fn();+ vi.mock("../api/rpc", () => ({+ callTool: (...args: unknown[]) => callToolMock(...args),+ }));++ describe("useProjects machine-readable pagination", () => {+ beforeEach(() => callToolMock.mockReset());++ it("requests JSON and merges every project and schema page", async () => {+ callToolMock.mockImplementation(async (name: string, args: Record<string, unknown>) => {+ if (name === "list_projects") {+ if (args.offset === 0) {+ return {+ projects: [{ name: "alpha", root_path: "/alpha", indexed_at: "now" }],+ has_more: true,+ next_offset: 1,+ };+ }+ return {+ projects: [{ name: "beta", root_path: "/beta", indexed_at: "now" }],+ has_more: false,+ };+ }+ if (name === "get_graph_schema" && args.project === "alpha") {+ if (args.offset === 0) {+ return {+ node_labels: [{ label: "Function", count: 3 }],+ edge_types: [],+ total_nodes: 3,+ total_edges: 2,+ has_more: true,+ next_offset: 1,+ };+ }+ return {+ node_labels: [],+ edge_types: [{ type: "CALLS", count: 2 }],+ total_nodes: 3,+ total_edges: 2,+ has_more: false,+ };+ }+ return {+ node_labels: [{ label: "Class", count: 1 }],+ edge_types: [],+ total_nodes: 1,+ total_edges: 0,+ has_more: false,+ };+ });++ const { result } = renderHook(() => useProjects());+ await waitFor(() => expect(result.current.loading).toBe(false));++ expect(result.current.projects).toHaveLength(2);- expect(result.current.projects[0].schema?.node_labels).toEqual([- { label: "Function", count: 3 },- ]);++ /* Schemas arrive after the list has rendered (lazy enrichment), so wait++ * for the merged pages rather than asserting them at loading=false. */++ await waitFor(() =>++ expect(result.current.projects[0].schema?.node_labels).toEqual([++ { label: "Function", count: 3 },++ ]),++ );+ expect(result.current.projects[0].schema?.edge_types).toEqual([+ { type: "CALLS", count: 2 },+ ]);+ expect(callToolMock).toHaveBeenCalledWith("list_projects", {+ format: "json",+ detail: "stats",+ limit: 500,+ offset: 0,+ });+ expect(callToolMock).toHaveBeenCalledWith("list_projects", {+ format: "json",+ detail: "stats",+ limit: 500,+ offset: 1,+ });+ expect(callToolMock).toHaveBeenCalledWith("get_graph_schema", {+ project: "alpha",+ format: "json",+ limit: 500,+ offset: 1,+ });+ });+ });diff --cc graph-ui/src/hooks/useProjects.tsindex c4df265a9,7ed5d7511..f9ff704ae--- a/graph-ui/src/hooks/useProjects.ts+++ b/graph-ui/src/hooks/useProjects.ts@@@ -39,50 -87,24 +103,44 @@@ export function useProjects(): UseProjesetLoading(true);setError(null);try {- /* include_details carries node/edge totals and indexed_at — without it- * the tool returns names only and every count would need a schema scan. */- const result = await callTool<{ projects: Project[] }>("list_projects", {- include_details: true,- limit: 100,- });++ /* Paginated, format json, detail stats: node/edge totals and indexed_at++ * come with the list, so every card renders before any schema scan. */+ const list = await fetchAllProjects();+ if (generation !== generationRef.current) return;- const list = result.projects ?? [];- /* Fetch schema for each project */- const infos: ProjectInfo[] = await Promise.all(- list.map(async (p) => {- try {- const schema = await fetchFullSchema(p.name);- return { project: p, schema };- } catch {- return { project: p, schema: null };- }- }),+ /* Render immediately from list_projects' own totals… */+ setProjects(+ list.map((p) => ({ project: p, schema: schemaCache.get(p.name) ?? null })),);+ setLoading(false);- setProjects(infos);+ /* …then enrich small projects with per-label schemas, one at a time,+ * patching each card as its schema lands. Sequential on purpose — N+ * parallel scans would serialize behind the store lock anyway — and+ * abandoned as soon as the tab unmounts or refreshes. */+ const candidates = list+ .filter(- (p) => !schemaCache.has(p.name) && (p.nodes ?? Infinity) <= SCHEMA_LAZY_MAX_NODES,++ (p) => !schemaCache.has(p.name) && (p.nodes ?? 0) <= SCHEMA_LAZY_MAX_NODES,+ )+ .slice(0, SCHEMA_LAZY_MAX_PROJECTS);+ for (const p of candidates) {+ if (generation !== generationRef.current) return;+ try {- const schema = await callTool<SchemaInfo>("get_graph_schema", {- project: p.name,- });++ const schema = await fetchFullSchema(p.name);+ schemaCache.set(p.name, schema);+ if (generation !== generationRef.current) return;+ setProjects((prev) =>+ prev.map((info) =>+ info.project.name === p.name ? { ...info, schema } : info,+ ),+ );+ } catch {+ /* card keeps its totals; chips stay absent */+ }+ }} catch (e) {+ if (generation !== generationRef.current) return;setError(e instanceof Error ? e.message : "Failed to fetch projects");- } finally {setLoading(false);}}, []);diff --cc scripts/run-test-wave.pyindex 18876d7c9,99f61bfd4..0f0ce463e--- a/scripts/run-test-wave.py+++ b/scripts/run-test-wave.py@@@ -25,26 -25,23 +25,40 @@@ SUITE_NAME = re.compile(r"^[a-z0-9_]+$"SUMMARY = re.compile(r"^ (?P<passed>[0-9]+) passed")FAILED = re.compile(r"(?:^|, )(?P<failed>[0-9]+) failed")SKIPPED = re.compile(r"(?:^|, )(?P<skipped>[0-9]+) skipped")-SLOW_SUITES = frozenset(("incremental", "store_arch", "daemon_runtime"))+# Suites on the slow tier carry a stated reason (O10: no unexplained+# entries). incremental/store_arch/daemon_runtime: the heaviest sanitized+# suites by steady-state cost. node_creation_probe/grammar_probe_b: full-+# pipeline indexing probes whose FIRST run in a fresh checkout pays a+# one-time environment tax (every artifact is AV-scan-cold on the Windows+# VM; grammar_probe_b hit it 2026-08-? under host contention, node_creation+# _probe 2026-08-28 at exactly 900s on a new run checkout, both green on+# the warm rerun). That state is deterministic, not racy — the stable-state+# budget rule applies.+SLOW_SUITES = frozenset(+ (+ "incremental",+ "store_arch",+ "daemon_runtime",+ "node_creation_probe",+ "grammar_probe_b",+ )+)POLL_SECONDS = 0.05+ # WHY: the Windows descendant probe below is a cold `powershell.exe` + CIM+ # start. On a GitHub Windows runner that routinely costs seconds -- interpreter+ # start-up, module autoload, CIM service warm-up -- and that cost is unrelated+ # to the state of the tree being proven. --kill-grace bounds how long a+ # *process* may resist termination and CI passes 1s, so timing the probe with+ # it made the proof a function of interpreter latency instead of the tree: a+ # cold start blew the 1s budget, TimeoutExpired became "assume the worst", and+ # an already-clean shard exited 2. This is a stable-state budget, not a race+ # tune -- the answer does not change with waiting, the budget only has to cover+ # a cold start, and a probe that still cannot finish is reported as an+ # unfinished probe rather than as a leaked tree.+ WINDOWS_DESCENDANT_PROBE_SECONDS = 15+ WINDOWS_DESCENDANT_PROBE_ATTEMPTS = 2+@dataclassclass ActiveSuite:diff --cc src/main.cindex 92c667b90,8a575c44f..0ffa02fb7--- a/src/main.c+++ b/src/main.c@@@ -1617,10 -1638,11 +1659,11 @@@ static char *main_local_cli_daemon_exec.identity = &identity,.executable_path = executable_path,.connect_timeout_ms = MAIN_CONNECT_TIMEOUT_MS,- .startup_timeout_ms = MAIN_MCP_STARTUP_TIMEOUT_MS,+ .startup_timeout_ms = main_startup_timeout_ms(),};cbm_daemon_bootstrap_result_t bootstrap;- cbm_daemon_bootstrap_status_t status = main_client_bootstrap_with_upgrade(&config, &bootstrap);+ cbm_daemon_bootstrap_status_t status =+ main_client_bootstrap_with_upgrade(&config, &bootstrap, !quiet_requested);cbm_daemon_ipc_endpoint_free(endpoint);if (status != CBM_DAEMON_BOOTSTRAP_CONNECTED || !bootstrap.client) {(void)fprintf(stderr, "error: %s\n",diff --cc src/mcp/mcp.cindex b75cc4c27,827f0e9f9..9cd96d2ce--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@@ -685,28 -726,27 +726,37 @@@ static const tool_def_t TOOLS[] ="\"required\":""[\"project\"]}"},- {"manage_adr", "Manage ADR", "Create or update Architecture Decision Records",+ {"manage_adr", "Outline an ADR by default; get reads it; update replaces it","{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"mode\":{\"type\":"- "\"string\",\"enum\":[\"get\",\"update\",\"sections\"],\"description\":\"update replaces "- "the entire ADR document; sections only lists existing "- "headings\"},\"content\":{\"type\":\"string\",\"description\":\"Complete replacement document "- "required by update\"}},\"additionalProperties\":false,"+ "\"string\",\"enum\":[\"outline\",\"get\",\"update\",\"set_sections\",\"sections\"],"+ "\"default\":\"outline\",\"description\":\"outline pages headings; get reads; update replaces "+ "the whole document; set_sections rewrites only the named sections and leaves every other "+ "byte untouched (an identical repeated write is byte-identical, so retrying is safe); "+ "sections is legacy.\"},"+ "\"content\":{\"type\":\"string\",\"description\":\"Whole document for update\"},"+ "\"section_updates\":{\"type\":\"object\",\"description\":\"set_sections: section name -> "+ "new body. Any heading name works; names match exactly, including case.\","+ "\"additionalProperties\":{\"type\":\"string\"}},"+ "\"section_limit\":{\"type\":\"integer\",\"default\":50,\"minimum\":1,\"maximum\":500},"+ "\"section_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"+ "\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},"+ "\"additionalProperties\":false,""\"required\":[\"project\"]}"},- {"ingest_traces", "Ingest traces",- {"ingest_traces", "Validate and count traces; graph edge creation is not implemented",++ {"ingest_traces",+ "Record observed runtime calls so the graph can distinguish observed from merely possible "+ "paths. Each trace is a call path (qualified names, adjacent = caller\xe2\x86\x92"+ "callee) or a bare caller/callee pair. Stored per run label, keyed by qualified name "+ "(reindex-proof). Only pairs whose both endpoints are indexed symbols are stored; the "+ "response reports unresolved names (up to 10) so the producer can fix its naming.","{\"type\":\"object\",\"properties\":{\"traces\":{\"type\":\"array\",\"items\":{\"type\":"- "\"object\",\"properties\":{\"caller\":{\"type\":\"string\"},\"callee\":{\"type\":\"string\"},"- "\"count\":{\"type\":\"integer\"}},\"additionalProperties\":false}},\"project\":{\"type\":"+ "\"object\",\"properties\":{\"path\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"+ "\"description\":\"Call path of qualified names, caller before callee; 2..256 entries\"},"+ "\"caller\":{\"type\":\"string\"},\"callee\":{\"type\":\"string\"},"+ "\"count\":{\"type\":\"integer\",\"description\":\"How often this trace was observed "+ "(default 1)\"}},\"additionalProperties\":false}},\"label\":{\"type\":\"string\","+ "\"description\":\"Run identity, e.g. 'pytest 2026-08-27' (default 'unlabeled'); counts "+ "accumulate per label and whole runs age out together\"},\"project\":{\"type\":""\"string\"}},\"required\":[\"traces\",\"project\"]}"},};@@@ -8353,25 -11085,9 +11095,28 @@@ static char *handle_index_repository(cbsrv, doc, root, project_name, repo_path, persistence, p, excluded_dirs, excluded_count,file_errors, file_error_count, has_logfile ? logfile_path : NULL);yyjson_mut_obj_add_str(doc, root, "status", degraded ? "degraded" : "indexed");+ if (cbm_pipeline_had_format_migration(p)) {+ yyjson_mut_obj_add_bool(doc, root, "format_migration", true);+ }+ } else if (rc == CBM_PIPELINE_ABORT_PRESERVE_DB) {+ /* The truthful abort message: the old generic "check repo_path" hint+ * sent people debugging a path that was fine, when the run aborted+ * pre-publication (semantic inputs changed mid-run, or a discovery/+ * manifest phase failed transiently) and the previous index is+ * intact. A 99-test cascade on the Windows leg traced back to+ * exactly this — the response said error, but not which kind. */+ yyjson_mut_obj_add_str(doc, root, "status", "aborted_previous_preserved");+ yyjson_mut_obj_add_str(doc, root, "hint",+ "Indexing aborted before publication; the previous index is "+ "intact and still serving. Causes: files changed while the run "+ "was in flight, or a discovery/manifest phase failed "+ "transiently. Retry; if it repeats, check the run log.");+ } else if (rc == CBM_PIPELINE_PERSIST_FAILED) {+ yyjson_mut_obj_add_str(doc, root, "status", "persist_failed");+ yyjson_mut_obj_add_str(doc, root, "hint",+ "The validated staging database could not be published. Check "+ "free disk space and permissions on the cache directory; the "+ "previous index may have been rolled back.");} else {yyjson_mut_obj_add_str(doc, root, "status", "error");yyjson_mut_obj_add_str(doc, root, "hint",@@@ -11301,10 -16904,10 +16933,10 @@@ static char *handle_manage_adr(cbm_mcp_invalidate_cached_store(srv);resolved = NULL;store = NULL;- resolved = resolve_store_internal(srv, project, true, false, NULL);+ resolved = resolve_store_internal(srv, project, true, false, NULL, true);}if (resolved) {- store = open_adr_store_for_write(srv, resolved, &owned_rw);+ store = open_store_for_write(srv, resolved, &owned_rw);if (store) {have_adr = (cbm_store_adr_get(store, project, &adr) == CBM_STORE_OK);if (!have_adr &&diff --cc src/ui/http_server.cindex 2a8a7f5a2,f47ac59be..21cce306b--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@@ -147,8 -151,10 +155,9 @@@ static void handle_ui_config(cbm_http_c* audit forbids hardcoded external URLs in graph-ui source (external* targets must come from an auditable backend response, same pattern as* the /api/repo-info deep-links). */- cbm_http_replyf(c, 200, g_cors_json, "{\"lang\":\"%s\",\"upstream_issues_url\":\"%s\"}",- lang_buf, "https://github.com/DeusData/codebase-memory-mcp/issues/new");+ cbm_http_replyf(c, 200, g_cors_json,- "{\"lang\":\"%s\",\"version\":\"%s\",\"upstream_issues_url\":\"%s\"}",- lang_buf, CBM_VERSION,- "https://github.com/DeusData/codebase-memory-mcp/issues/new");++ "{\"lang\":\"%s\",\"version\":\"%s\",\"upstream_issues_url\":\"%s\"}", lang_buf,++ CBM_VERSION, "https://github.com/DeusData/codebase-memory-mcp/issues/new");}/* ── Server state ─────────────────────────────────────────────── */diff --cc tests/test_httpd.cindex dd49075c0,8cc0c1772..537592345--- a/tests/test_httpd.c+++ b/tests/test_httpd.c@@@ -1086,18 -1172,10 +1172,18 @@@ TEST(ui_server_mutations_require_json_cTEST(ui_server_rpc_allows_only_ui_read_tools) {th_server_t ts;ASSERT_EQ(th_server_start(&ts), 0);+ /* CBM Atlas reads the graph through /rpc: every read-only query tool must+ * pass the allowlist (a 403 on get_graph_schema is #1663). HTTP 200 means+ * "allowed and dispatched" — tool-level argument errors still ride inside+ * a 200 JSON-RPC envelope. */+ static const char *allowed_tools[] = {+ "list_projects", "get_code_snippet", "get_graph_schema", "search_graph",+ "search_code", "trace_path", "trace_call_path", "get_architecture",+ "query_graph", "detect_changes", "check_index_coverage", "index_status",+ };char req[1024];char resp[8192];- int n;+ int n = 0;- static const char *allowed_tools[] = {"list_projects", "get_graph_schema", "get_code_snippet"};for (size_t i = 0; i < sizeof(allowed_tools) / sizeof(allowed_tools[0]); i++) {char body[512];snprintf(body, sizeof(body),diff --cc tests/test_mcp.cindex 1940f48de,ef7823a12..3c418c117--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@@ -3009,127 -5397,545 +5397,662 @@@ TEST(tool_index_status_no_project)PASS();}- /* ══════════════════════════════════════════════════════════════════- * TOOL HANDLERS WITH DATA- * ══════════════════════════════════════════════════════════════════ */-- TEST(tool_trace_call_path_not_found) {++/* ingest_traces stores observed runtime calls qn-keyed (reindex-proof):++ * paths decompose into pairs, counts accumulate per run label, unresolved++ * names are reported (not silently dropped), whole runs evict together. */++TEST(tool_ingest_traces_stores_observed_calls) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);++ ASSERT_NOT_NULL(srv);++ cbm_store_t *st = cbm_mcp_server_store(srv);++ ASSERT_NOT_NULL(st);++ const char *project = "traces-test";++ ASSERT_EQ(cbm_store_upsert_project(st, project, "/tmp/traces-test"), CBM_STORE_OK);++ cbm_mcp_server_set_project(srv, project);+- char *resp =- cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":20,\"method\":\"tools/call\","- "\"params\":{\"name\":\"trace_call_path\","- "\"arguments\":{\"function_name\":\"NonExistent\","- "\"project\":\"nonexistent\"}}}");++ static const char *const names[3] = {"alpha", "beta", "gamma"};++ for (int i = 0; i < 3; i++) {++ cbm_node_t node;++ memset(&node, 0, sizeof(node));++ node.project = project;++ node.label = "Function";++ node.name = names[i];++ char qn[64];++ snprintf(qn, sizeof(qn), "traces-test::%s", names[i]);++ node.qualified_name = qn;++ node.file_path = "src/t.c";++ node.start_line = 1;++ node.end_line = 3;++ ASSERT_GT(cbm_store_upsert_node(st, &node), 0);++ }++++ /* One 3-hop path, one bare pair with a count, one path with an++ * unindexed hop (skipped, reported), one malformed 1-hop path. */++ char *resp = cbm_mcp_handle_tool(++ srv, "ingest_traces",++ "{\"project\":\"traces-test\",\"label\":\"run1\",\"traces\":["++ "{\"path\":[\"traces-test::alpha\",\"traces-test::beta\",\"traces-test::gamma\"]},"++ "{\"caller\":\"traces-test::alpha\",\"callee\":\"traces-test::gamma\",\"count\":5},"++ "{\"path\":[\"traces-test::alpha\",\"traces-test::missing\"]},"++ "{\"path\":[\"traces-test::alpha\"]}]}");+ ASSERT_NOT_NULL(resp);- /* Should return error about project not found */- ASSERT_NOT_NULL(strstr(resp, "not found"));++ char *inner = extract_text_content(resp);++ ASSERT_NOT_NULL(inner);++ ASSERT_NOT_NULL(strstr(inner, "\"status\":\"stored\""));++ ASSERT_NOT_NULL(strstr(inner, "\"pairs_stored\":3"));++ ASSERT_NOT_NULL(strstr(inner, "\"paths_stored\":1"));++ ASSERT_NOT_NULL(strstr(inner, "\"pairs_unmatched\":1"));++ ASSERT_NOT_NULL(strstr(inner, "traces-test::missing"));++ ASSERT_NOT_NULL(strstr(inner, "\"malformed\":1"));++ free(inner);+ free(resp);+- cbm_mcp_server_free(srv);- PASS();- }-- /* Regression for #1425: a project name that fails validation must produce a- * clean "not found" error and NOTHING else. project_db_path() yields "" for- * such names; SQLite opens "" as an anonymous temp db, its integrity check- * fails, and quarantine rendered "".corrupt.<hex> - a RELATIVE path dropped- * into the daemon's cwd on every such query. */- TEST(tool_call_invalid_project_name_leaves_no_corrupt_litter_issue1425) {- char tmpdir[256];- snprintf(tmpdir, sizeof(tmpdir), "/tmp/mcp-litter-XXXXXX");- if (!cbm_mkdtemp(tmpdir))- FAIL("cbm_mkdtemp failed");- char oldcwd[CBM_SZ_1K];- if (!cbm_getcwd(oldcwd, sizeof(oldcwd)))- FAIL("getcwd failed");- if (cbm_chdir(tmpdir) != 0)- FAIL("chdir failed");++ long long count = -1;++ char label[64], seen[64];++ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::beta",++ &count, label, sizeof(label), seen, sizeof(seen)),++ CBM_STORE_OK);++ ASSERT_EQ((int)count, 1);++ ASSERT_STR_EQ(label, "run1");++ ASSERT_TRUE(seen[0] != '\0');++ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::gamma",++ &count, NULL, 0, NULL, 0),++ CBM_STORE_OK);++ ASSERT_EQ((int)count, 5);++ /* Never observed: zero count, not an error. */++ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::beta", "traces-test::alpha",++ &count, NULL, 0, NULL, 0),++ CBM_STORE_OK);++ ASSERT_EQ((int)count, 0);+- cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);- char *resp =- cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":30,\"method\":\"tools/call\","- "\"params\":{\"name\":\"search_graph\","- "\"arguments\":{\"name_pattern\":\"x\","- "\"project\":\"bad name\"}}}");- bool clean_error = resp && strstr(resp, "not found") != NULL;++ /* Same pair again under the same label accumulates; a second label++ * aggregates in the lookup and reports as the newest run. */++ resp = cbm_mcp_handle_tool(++ srv, "ingest_traces",++ "{\"project\":\"traces-test\",\"label\":\"run1\",\"traces\":[{\"caller\":"++ "\"traces-test::alpha\",\"callee\":\"traces-test::gamma\",\"count\":2}]}");++ ASSERT_NOT_NULL(resp);+ free(resp);- cbm_mcp_server_free(srv);-- int litter = 0;- cbm_dir_t *dir = cbm_opendir(tmpdir);- if (dir) {- cbm_dirent_t *entry;- while ((entry = cbm_readdir(dir)) != NULL) {- if (strstr(entry->name, ".corrupt.")) {- litter++;- }- }- cbm_closedir(dir);- }- if (cbm_chdir(oldcwd) != 0)- FAIL("chdir back failed");- th_rmtree(tmpdir);- if (!clean_error)- FAIL("invalid project name must produce a clean not-found error");- if (litter != 0)- FAIL("invalid project name must not quarantine an anonymous temp db into cwd (#1425)");- PASS();- }++ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::gamma",++ &count, NULL, 0, NULL, 0),++ CBM_STORE_OK);++ ASSERT_EQ((int)count, 7);++ resp = cbm_mcp_handle_tool(++ srv, "ingest_traces",++ "{\"project\":\"traces-test\",\"label\":\"run2\",\"traces\":[{\"caller\":"++ "\"traces-test::alpha\",\"callee\":\"traces-test::beta\"}]}");++ ASSERT_NOT_NULL(resp);++ free(resp);++ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::beta",++ &count, label, sizeof(label), NULL, 0),++ CBM_STORE_OK);++ ASSERT_EQ((int)count, 2);++ ASSERT_STR_EQ(label, "run2");+- TEST(tool_trace_missing_function_name) {- cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);++ /* Whole-run eviction: run1's newest observation is older, so run1 goes++ * first and run2 survives intact. */++ char *evicted = NULL;++ ASSERT_EQ(cbm_store_observed_evict_oldest_label(st, project, &evicted), CBM_STORE_OK);++ ASSERT_NOT_NULL(evicted);++ ASSERT_STR_EQ(evicted, "run1");++ free(evicted);++ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::gamma",++ &count, NULL, 0, NULL, 0),++ CBM_STORE_OK);++ ASSERT_EQ((int)count, 0);++ ASSERT_EQ(cbm_store_observed_lookup(st, project, "traces-test::alpha", "traces-test::beta",++ &count, NULL, 0, NULL, 0),++ CBM_STORE_OK);++ ASSERT_EQ((int)count, 1);+- char *resp =- cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":21,\"method\":\"tools/call\","- "\"params\":{\"name\":\"trace_call_path\","- "\"arguments\":{}}}");++ /* Empty traces is a tool error, not a silent accept. */++ resp = cbm_mcp_handle_tool(srv, "ingest_traces", "{\"project\":\"traces-test\",\"traces\":[]}");+ ASSERT_NOT_NULL(resp);- ASSERT_NOT_NULL(strstr(resp, "required"));++ ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));+ free(resp);++ cbm_mcp_server_free(srv);+ PASS();+}+- /* Regression: two same-named definitions with equal rank must be reported- * ambiguous, not silently traced (trace_path previously took nodes[0]). */- TEST(tool_trace_call_path_ambiguous) {+ /* Reproduce the exact-file false negative in the current Read hook: index_status+ * intentionally caps each coverage category at 500 entries, so a later path is+ * absent even though the authoritative index_coverage table contains it. The+ * targeted coverage tool must query that table rather than scan the capped+ * presentation response. */+ TEST(tool_check_index_coverage_finds_path_beyond_status_cap) {+ enum { ROW_COUNT = 502 };cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);cbm_store_t *st = cbm_mcp_server_store(srv);- const char *proj = "amb-proj";- cbm_mcp_server_set_project(srv, proj);- cbm_store_upsert_project(st, proj, "/tmp/amb");- cbm_node_t a = {.project = proj,- .label = "Function",- .name = "amb",- .qualified_name = "amb-proj.a.amb",- .file_path = "a.c",- .start_line = 10,- .end_line = 20};- cbm_node_t b = {.project = proj,- .label = "Function",- .name = "amb",- .qualified_name = "amb-proj.b.amb",- .file_path = "b.c",- .start_line = 10,- .end_line = 20}; /* equal span -> genuine tie */- ASSERT_GT(cbm_store_upsert_node(st, &a), 0);- ASSERT_GT(cbm_store_upsert_node(st, &b), 0);+ ASSERT_NOT_NULL(st);- char *resp = cbm_mcp_server_handle(- srv, "{\"jsonrpc\":\"2.0\",\"id\":61,\"method\":\"tools/call\","- "\"params\":{\"name\":\"trace_call_path\","- "\"arguments\":{\"function_name\":\"amb\",\"project\":\"amb-proj\"}}}");- ASSERT_NOT_NULL(resp);- char *inner = extract_text_content(resp);- ASSERT_NOT_NULL(inner);- ASSERT_NOT_NULL(strstr(inner, "ambiguous"));- ASSERT_NOT_NULL(strstr(inner, "suggestions"));- ASSERT_NULL(strstr(inner, "\"callees\""));- free(inner);- free(resp);+ const char *project = "coverage-cap-regression";+ ASSERT_EQ(cbm_store_upsert_project(st, project, "/tmp/coverage-cap-regression"), CBM_STORE_OK);+ cbm_mcp_server_set_project(srv, project);++ char (*paths)[64] = calloc(ROW_COUNT, sizeof(*paths));+ cbm_coverage_row_t *rows = calloc(ROW_COUNT, sizeof(*rows));+ ASSERT_NOT_NULL(paths);+ ASSERT_NOT_NULL(rows);+ for (int i = 0; i < ROW_COUNT; i++) {+ snprintf(paths[i], sizeof(paths[i]), "src/partial-%04d.c", i);+ rows[i].rel_path = paths[i];+ rows[i].kind = "parse_partial";+ rows[i].detail = i == ROW_COUNT - 1 ? "777-790" : "1-2";+ ASSERT_EQ(cbm_store_upsert_file_hash(st, project, paths[i], "fixture", i + 1, 10),+ CBM_STORE_OK);+ }+ ASSERT_EQ(cbm_store_coverage_replace(st, project, rows, ROW_COUNT), CBM_STORE_OK);++ char *status = cbm_mcp_handle_tool(+ srv, "index_status",+ "{\"project\":\"coverage-cap-regression\",\"diagnostics\":\"full\",\"format\":\"json\"}");+ ASSERT_NOT_NULL(status);+ char *status_inner = extract_text_content(status);+ ASSERT_NOT_NULL(status_inner);+ ASSERT_NOT_NULL(strstr(status_inner, "\"truncated\":true"));+ ASSERT_NULL(strstr(status_inner, "src/partial-0501.c"));+ free(status_inner);+ free(status);++ char *coverage = cbm_mcp_handle_tool(+ srv, "check_index_coverage",+ "{\"project\":\"coverage-cap-regression\",\"paths\":[\"src/partial-0501.c\"],"+ "\"format\":\"json\"}");+ ASSERT_NOT_NULL(coverage);+ char *coverage_inner = extract_text_content(coverage);+ ASSERT_NOT_NULL(coverage_inner);+ ASSERT_NOT_NULL(strstr(coverage_inner, "src/partial-0501.c"));+ ASSERT_NOT_NULL(strstr(coverage_inner, "\"status\":\"partial\""));+ ASSERT_NOT_NULL(strstr(coverage_inner, "\"start\":777"));+ ASSERT_NOT_NULL(strstr(coverage_inner, "\"end\":790"));+ ASSERT_NULL(strstr(coverage_inner, "\"detail\":\"777-790\""));++ free(coverage_inner);+ free(coverage);+ free(rows);+ free(paths);+ cbm_mcp_server_free(srv);+ PASS();+ }++ TEST(tool_check_index_coverage_pages_exact_paths_and_restores_raw_diagnostics) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(store);+ const char *project = "coverage-path-page";+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/coverage-path-page"), CBM_STORE_OK);+ cbm_mcp_server_set_project(srv, project);+ cbm_coverage_row_t row = {+ .rel_path = "path-00.c", .kind = "parse_partial", .detail = "11-19,27"};+ ASSERT_EQ(cbm_store_upsert_file_hash(store, project, "path-00.c", "fixture", 1, 1),+ CBM_STORE_OK);+ ASSERT_EQ(cbm_store_coverage_replace(store, project, &row, 1), CBM_STORE_OK);+ cbm_coverage_row_t *stored_rows = NULL;+ int stored_count = 0;+ ASSERT_EQ(cbm_store_coverage_get_path(store, project, "path-00.c", &stored_rows, &stored_count),+ CBM_STORE_OK);+ ASSERT_EQ(stored_count, 1);+ cbm_store_free_coverage(stored_rows, stored_count);++ char args[4096];+ size_t used =+ (size_t)snprintf(args, sizeof(args), "{\"project\":\"coverage-path-page\",\"paths\":[");+ for (int i = 0; i < 25; i++) {+ used += (size_t)snprintf(args + used, sizeof(args) - used, "%s\"path-%02d.c\"",+ i ? "," : "", i);+ }+ (void)snprintf(args + used, sizeof(args) - used, "],\"format\":\"json\"}");++ char *response = cbm_mcp_handle_tool(srv, "check_index_coverage", args);+ ASSERT_NOT_NULL(response);+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ yyjson_doc *doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *root = yyjson_doc_get_root(doc);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "path_total")), 25);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "path_returned")), 20);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "path_has_more")));+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "path_next_offset")), 20);+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "paths")), 20);+ ASSERT_NOT_NULL(strstr(inner, "\"start\":11"));+ ASSERT_NULL(strstr(inner, "\"detail\":\"11-19,27\""));+ ASSERT_NULL(strstr(inner, "path-20.c"));+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ used = (size_t)snprintf(args, sizeof(args), "{\"project\":\"coverage-path-page\",\"paths\":[");+ for (int i = 0; i < 25; i++) {+ used += (size_t)snprintf(args + used, sizeof(args) - used, "%s\"path-%02d.c\"",+ i ? "," : "", i);+ }+ (void)snprintf(args + used, sizeof(args) - used,+ "],\"path_offset\":20,\"diagnostics\":\"full\",\"format\":\"json\"}");+ response = cbm_mcp_handle_tool(srv, "check_index_coverage", args);+ ASSERT_NOT_NULL(response);+ inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ root = yyjson_doc_get_root(doc);+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(root, "path_returned")), 5);+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(root, "path_has_more")));+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(root, "paths")), 5);+ ASSERT_NOT_NULL(strstr(inner, "path-20.c"));+ yyjson_doc_free(doc);+ free(inner);+ free(response);++ char *full =+ cbm_mcp_handle_tool(srv, "check_index_coverage",+ "{\"project\":\"coverage-path-page\",\"paths\":[\"path-00.c\"],"+ "\"diagnostics\":\"full\",\"format\":\"json\"}");+ ASSERT_NOT_NULL(full);+ char *full_inner = extract_text_content(full);+ ASSERT_NOT_NULL(full_inner);+ ASSERT_NOT_NULL(strstr(full_inner, "\"detail\":\"11-19,27\""));+ free(full_inner);+ free(full);++ cbm_mcp_server_free(srv);+ PASS();+ }++ TEST(tool_check_index_coverage_reports_paths_scopes_and_ranges) {+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(st);++ ASSERT_EQ(cbm_store_upsert_file_hash(st, "test-project", "main.go", "", 0, 0), CBM_STORE_OK);+ ASSERT_EQ(cbm_store_upsert_file_hash(st, "test-project", "src/skip.c", "", 0, 0), CBM_STORE_OK);+ cbm_coverage_row_t rows[] = {+ {.rel_path = "main.go", .kind = "parse_partial", .detail = "3-4,9"},+ {.rel_path = "generated", .kind = "not_indexed_dir", .detail = "excluded subtree"},+ {.rel_path = "src/skip.c", .kind = "oversized", .detail = "file exceeds cap"},+ };+ ASSERT_EQ(cbm_store_coverage_replace(st, "test-project", rows, 3), CBM_STORE_OK);++ char *coverage =+ cbm_mcp_handle_tool(srv, "check_index_coverage",+ "{\"project\":\"test-project\","+ "\"paths\":[\"main.go\",\"generated/pkg/a.c\",\"../escape.c\"],"+ "\"scopes\":[\".\"],\"format\":\"json\"}");+ ASSERT_NOT_NULL(coverage);+ char *inner = extract_text_content(coverage);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"path\":\"main.go\""));+ ASSERT_NOT_NULL(strstr(inner, "\"status\":\"partial\""));+ ASSERT_NOT_NULL(strstr(inner, "\"start\":3"));+ ASSERT_NOT_NULL(strstr(inner, "\"end\":4"));+ ASSERT_NOT_NULL(strstr(inner, "\"start\":9"));+ ASSERT_NOT_NULL(strstr(inner, "generated/pkg/a.c"));+ ASSERT_NOT_NULL(strstr(inner, "not_indexed_dir"));+ ASSERT_NOT_NULL(strstr(inner, "outside_project"));+ ASSERT_NOT_NULL(strstr(inner, "src/skip.c"));+ ASSERT_NOT_NULL(strstr(inner, "file exceeds cap"));+ ASSERT_NOT_NULL(strstr(inner, "best_effort"));++ free(inner);+ free(coverage);+ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+ }++ TEST(tool_check_index_coverage_preserves_multiple_scope_labels) {+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);++ char *coverage = cbm_mcp_handle_tool(srv, "check_index_coverage",+ "{\"project\":\"test-project\","+ "\"scopes\":[\"alpha/one\",\"bravo/two\",\"charl/tri\"],"+ "\"format\":\"json\"}");+ ASSERT_NOT_NULL(coverage);+ char *inner = extract_text_content(coverage);+ ASSERT_NOT_NULL(inner);+ yyjson_doc *doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *scopes = yyjson_obj_get(yyjson_doc_get_root(doc), "scopes");+ ASSERT_NOT_NULL(scopes);+ ASSERT_TRUE(yyjson_is_arr(scopes));+ ASSERT_EQ(yyjson_arr_size(scopes), 3);++ const char *expected[] = {"alpha/one", "bravo/two", "charl/tri"};+ for (size_t i = 0; i < 3; i++) {+ yyjson_val *scope = yyjson_obj_get(yyjson_arr_get(scopes, i), "scope");+ ASSERT_NOT_NULL(scope);+ ASSERT_TRUE(yyjson_is_str(scope));+ ASSERT_STR_EQ(yyjson_get_str(scope), expected[i]);+ }++ yyjson_doc_free(doc);+ free(inner);+ free(coverage);+ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+ }++ static int write_coverage_meta(cbm_store_t *store, const char *generation,+ const char *recording_status) {+ cbm_coverage_meta_t meta = {+ .generation = generation,+ .index_mode = "fast",+ .recorded_at = "2026-07-12T00:00:00Z",+ .recording_status = recording_status,+ .ignored_files_stored = 0,+ .ignored_files_total = 0,+ .coverage_version = 1,+ .hash_records_complete = true,+ };+ return cbm_store_coverage_replace_ex(store, "test-project", NULL, 0, &meta);+ }++ TEST(tool_check_index_coverage_accepts_truncated_ignored_catalog_for_fresh_path_issue1613) {+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(store);+ char source_path[512];+ snprintf(source_path, sizeof(source_path), "%s/project/main.go", tmp);+ struct stat source_stat;+ ASSERT_EQ(stat(source_path, &source_stat), 0);+ #ifdef __APPLE__+ int64_t source_mtime_ns =+ ((int64_t)source_stat.st_mtimespec.tv_sec * (int64_t)CBM_NSEC_PER_SEC) ++ (int64_t)source_stat.st_mtimespec.tv_nsec;+ #elif defined(_WIN32)+ int64_t source_mtime_ns = (int64_t)source_stat.st_mtime * (int64_t)CBM_NSEC_PER_SEC;+ #else+ int64_t source_mtime_ns = ((int64_t)source_stat.st_mtim.tv_sec * (int64_t)CBM_NSEC_PER_SEC) ++ (int64_t)source_stat.st_mtim.tv_nsec;+ #endif+ ASSERT_EQ(cbm_store_upsert_file_hash(store, "test-project", "main.go", "", source_mtime_ns,+ source_stat.st_size),+ CBM_STORE_OK);+ cbm_project_t project = {0};+ ASSERT_EQ(cbm_store_get_project(store, "test-project", &project), CBM_STORE_OK);+ cbm_coverage_meta_t meta = {+ .generation = project.indexed_at,+ .index_mode = "fast",+ .recorded_at = "2026-07-12T00:00:00Z",+ .recording_status = "truncated",+ .ignored_files_stored = 2000,+ .ignored_files_total = 2001,+ .coverage_version = 1,+ .hash_records_complete = true,+ };+ ASSERT_EQ(cbm_store_coverage_replace_ex(store, "test-project", NULL, 0, &meta), CBM_STORE_OK);+ cbm_project_free_fields(&project);++ char *response = cbm_mcp_handle_tool(+ srv, "check_index_coverage",+ "{\"project\":\"test-project\",\"paths\":[\"main.go\"],\"scopes\":[\".\"],"+ "\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ yyjson_doc *doc = yyjson_read(inner, strlen(inner), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *root = yyjson_doc_get_root(doc);+ yyjson_val *path = yyjson_arr_get(yyjson_obj_get(root, "paths"), 0);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(path, "status")), "no_recorded_issue");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(path, "freshness")), "metadata_match");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(path, "recommended_action")),+ "use_graph_with_best_effort_caveat");+ yyjson_val *scope = yyjson_arr_get(yyjson_obj_get(root, "scopes"), 0);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(scope, "status")), "coverage_unavailable");++ yyjson_doc_free(doc);+ free(inner);+ free(response);+ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+ }++ TEST(tool_check_index_coverage_rejects_stale_generation) {+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(store);+ ASSERT_EQ(write_coverage_meta(store, "stale-generation", "complete"), CBM_STORE_OK);++ char *response = cbm_mcp_handle_tool(srv, "check_index_coverage",+ "{\"project\":\"test-project\",\"paths\":[\"main.go\"],"+ "\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"generation_matches\":false"));+ ASSERT_NOT_NULL(strstr(inner, "\"status\":\"coverage_unavailable\""));+ ASSERT_NOT_NULL(strstr(inner, "\"recommended_action\":\"read_source_and_reindex\""));++ free(inner);+ free(response);+ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+ }++ TEST(tool_check_index_coverage_requires_source_when_file_metadata_changed) {+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(store);+ cbm_project_t project = {0};+ ASSERT_EQ(cbm_store_get_project(store, "test-project", &project), CBM_STORE_OK);+ ASSERT_EQ(write_coverage_meta(store, project.indexed_at, "complete"), CBM_STORE_OK);+ cbm_project_free_fields(&project);+ ASSERT_EQ(cbm_store_upsert_file_hash(store, "test-project", "main.go", "fixture", 0, 0),+ CBM_STORE_OK);++ char *response = cbm_mcp_handle_tool(srv, "check_index_coverage",+ "{\"project\":\"test-project\",\"paths\":[\"main.go\"],"+ "\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"generation_matches\":true"));+ ASSERT_NOT_NULL(strstr(inner, "\"freshness\":\"metadata_changed\""));+ ASSERT_NOT_NULL(strstr(inner, "\"recommended_action\":\"read_source_and_reindex\""));++ free(inner);+ free(response);+ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+ }++ TEST(tool_check_index_coverage_surfaces_lookup_errors) {+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(store);+ cbm_project_t project = {0};+ ASSERT_EQ(cbm_store_get_project(store, "test-project", &project), CBM_STORE_OK);+ ASSERT_EQ(write_coverage_meta(store, project.indexed_at, "complete"), CBM_STORE_OK);+ cbm_project_free_fields(&project);+ ASSERT_EQ(+ cbm_store_exec(store, "ALTER TABLE index_coverage RENAME COLUMN detail TO broken_detail;"),+ CBM_STORE_OK);++ char *response = cbm_mcp_handle_tool(+ srv, "check_index_coverage",+ "{\"project\":\"test-project\",\"paths\":[\"main.go\"],\"scopes\":[\".\"],"+ "\"format\":\"json\"}");+ ASSERT_NOT_NULL(response);+ char *inner = extract_text_content(response);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"coverage_lookup\":\"error\""));+ ASSERT_NOT_NULL(strstr(inner, "\"status\":\"coverage_unavailable\""));+ ASSERT_NULL(strstr(inner, "\"status\":\"no_recorded_issue\""));++ free(inner);+ free(response);+ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+ }++ TEST(tool_index_status_includes_git_metadata) {+ /* The git context block moved behind verbose:true (lean-default contract,+ * TOON round 2) — this test pins the verbose path's content; the default-+ * omission guard lives in tool_lean_defaults_schema_and_status. */+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);++ char *resp =+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":16,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"index_status\","+ "\"arguments\":{\"project\":\"test-project\",\"verbose\":true,"+ "\"format\":\"json\"}}}");+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"root_path\""));+ ASSERT_NOT_NULL(strstr(inner, "\"git\""));+ ASSERT_NOT_NULL(strstr(inner, "\"is_git\":false"));+ ASSERT_NOT_NULL(strstr(inner, "\"root_exists\":true"));++ free(inner);+ free(resp);+ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+ }++ /* ══════════════════════════════════════════════════════════════════+ * TOOL HANDLERS WITH DATA+ * ══════════════════════════════════════════════════════════════════ */++ TEST(tool_trace_call_path_not_found) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);++ char *resp =+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":20,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"trace_call_path\","+ "\"arguments\":{\"function_name\":\"NonExistent\","+ "\"project\":\"nonexistent\"}}}");+ ASSERT_NOT_NULL(resp);+ /* Should return error about project not found */+ ASSERT_NOT_NULL(strstr(resp, "not found"));+ free(resp);++ cbm_mcp_server_free(srv);+ PASS();+ }++ /* Regression for #1425: a project name that fails validation must produce a+ * clean "not found" error and NOTHING else. project_db_path() yields "" for+ * such names; SQLite opens "" as an anonymous temp db, its integrity check+ * fails, and quarantine rendered "".corrupt.<hex> - a RELATIVE path dropped+ * into the daemon's cwd on every such query. */+ TEST(tool_call_invalid_project_name_leaves_no_corrupt_litter_issue1425) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/mcp-litter-XXXXXX");+ if (!cbm_mkdtemp(tmpdir))+ FAIL("cbm_mkdtemp failed");+ char oldcwd[CBM_SZ_1K];+ if (!cbm_getcwd(oldcwd, sizeof(oldcwd)))+ FAIL("getcwd failed");+ if (cbm_chdir(tmpdir) != 0)+ FAIL("chdir failed");++ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ char *resp =+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":30,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"search_graph\","+ "\"arguments\":{\"name_pattern\":\"x\","+ "\"project\":\"bad name\"}}}");+ bool clean_error = resp && strstr(resp, "not found") != NULL;+ free(resp);+ cbm_mcp_server_free(srv);++ int litter = 0;+ cbm_dir_t *dir = cbm_opendir(tmpdir);+ if (dir) {+ cbm_dirent_t *entry;+ while ((entry = cbm_readdir(dir)) != NULL) {+ if (strstr(entry->name, ".corrupt.")) {+ litter++;+ }+ }+ cbm_closedir(dir);+ }+ if (cbm_chdir(oldcwd) != 0)+ FAIL("chdir back failed");+ th_rmtree(tmpdir);+ if (!clean_error)+ FAIL("invalid project name must produce a clean not-found error");+ if (litter != 0)+ FAIL("invalid project name must not quarantine an anonymous temp db into cwd (#1425)");+ PASS();+ }++ TEST(tool_trace_missing_function_name) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);++ char *resp =+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":21,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"trace_call_path\","+ "\"arguments\":{}}}");+ ASSERT_NOT_NULL(resp);+ ASSERT_NOT_NULL(strstr(resp, "required"));+ free(resp);++ cbm_mcp_server_free(srv);+ PASS();+ }++ /* Regression: two same-named definitions with equal rank must be reported+ * ambiguous, not silently traced (trace_path previously took nodes[0]). */+ TEST(tool_trace_call_path_ambiguous) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ const char *proj = "amb-proj";+ cbm_mcp_server_set_project(srv, proj);+ cbm_store_upsert_project(st, proj, "/tmp/amb");+ cbm_node_t a = {.project = proj,+ .label = "Function",+ .name = "amb",+ .qualified_name = "amb-proj.a.amb",+ .file_path = "a.c",+ .start_line = 10,+ .end_line = 20};+ cbm_node_t b = {.project = proj,+ .label = "Function",+ .name = "amb",+ .qualified_name = "amb-proj.b.amb",+ .file_path = "b.c",+ .start_line = 10,+ .end_line = 20}; /* equal span -> genuine tie */+ ASSERT_GT(cbm_store_upsert_node(st, &a), 0);+ ASSERT_GT(cbm_store_upsert_node(st, &b), 0);++ char *resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":61,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"trace_call_path\","+ "\"arguments\":{\"function_name\":\"amb\",\"project\":\"amb-proj\"}}}");+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "ambiguous"));+ ASSERT_NOT_NULL(strstr(inner, "suggestions"));+ ASSERT_NULL(strstr(inner, "\"callees\""));+ free(inner);+ free(resp);cbm_mcp_server_free(srv);PASS();}@@@ -11456,12 -19949,26 +20081,27 @@@ SUITE(mcp)RUN_TEST(tool_output_regression_gate);RUN_TEST(tool_output_byte_budgets);RUN_TEST(tool_search_graph_query_honors_file_pattern_issue552);+ RUN_TEST(tool_search_graph_bm25_reports_candidate_saturation);+ RUN_TEST(tool_search_graph_rejects_bm25_and_semantic_query_together);+ RUN_TEST(tool_search_graph_semantic_ceiling_never_emits_unusable_continuation);+ RUN_TEST(tool_search_graph_semantic_pagination_is_lossless_and_independent);+ RUN_TEST(tool_search_graph_semantic_query_rejects_non_string_elements);+ RUN_TEST(tool_search_graph_semantic_store_error_fails_closed);+ RUN_TEST(tool_search_graph_budget_preserves_long_values_and_continuation);RUN_TEST(mcp_resource_discovery_methods_return_empty_lists);RUN_TEST(tool_query_graph_basic);+ RUN_TEST(tool_query_graph_default_budget_is_truthful_and_expandable);+ RUN_TEST(tool_query_graph_cursor_is_lossless_and_snapshot_bound);+ RUN_TEST(tool_query_graph_budget_bounds_first_row_and_json_escaping);+ RUN_TEST(tool_query_graph_prefix_directory_is_lossless_and_json_stays_direct);+ RUN_TEST(tool_query_graph_prefix_directory_recovers_rows_beyond_raw_estimate);+ RUN_TEST(tool_list_projects_tree_uses_one_stable_header_and_keeps_json_direct);+ RUN_TEST(tool_list_projects_preserves_root_beyond_one_kib);RUN_TEST(tool_index_status_no_project);+ RUN_TEST(tool_ingest_traces_stores_observed_calls);RUN_TEST(tool_check_index_coverage_finds_path_beyond_status_cap);RUN_TEST(tool_check_index_coverage_reports_paths_scopes_and_ranges);+ RUN_TEST(tool_check_index_coverage_pages_exact_paths_and_restores_raw_diagnostics);RUN_TEST(tool_check_index_coverage_preserves_multiple_scope_labels);RUN_TEST(tool_check_index_coverage_accepts_truncated_ignored_catalog_for_fresh_path_issue1613);RUN_TEST(tool_check_index_coverage_rejects_stale_generation);