Skip to content

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.

Fix memory leak in resolve_store + Windows setenv build error

Martin Vogel7d6b3af3412a
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index d126a82f0..8f497fa8c 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -653,9 +653,17 @@ static cbm_store_t *resolve_store(cbm_mcp_server_t *srv, const char *project) {
project_db_path(project, path, sizeof(path));
srv->store = cbm_store_open_path_query(path);
if (srv->store) {
- /* Only update ownership and cached project name on successful open.
- * When the file is absent, store is NULL and current_project retains
- * its previous value so the next call correctly retries the open. */
+ /* Verify the project actually exists in this database.
+ * A .db file may exist but be empty (e.g., after delete_project on
+ * Linux where unlink defers actual removal). Opening an empty/deleted
+ * store without closing it leaks the SQLite connection. */
+ cbm_project_t proj_verify = {0};
+ if (cbm_store_get_project(srv->store, project, &proj_verify) != CBM_STORE_OK) {
+ cbm_store_close(srv->store);
+ srv->store = NULL;
+ return NULL;
+ }
+ cbm_project_free_fields(&proj_verify);
srv->owns_store = true;
free(srv->current_project);
srv->current_project = heap_strdup(project);
diff --git a/tests/test_integration.c b/tests/test_integration.c
index 3d32f4229..bc6a713f8 100644
--- a/tests/test_integration.c
+++ b/tests/test_integration.c
@@ -410,7 +410,6 @@ TEST(integ_mcp_delete_project) {
snprintf(args, sizeof(args), "{\"label\":\"Function\",\"project\":\"%s\"}", g_project);
resp = call_tool("search_graph", args);
ASSERT_NOT_NULL(resp);
- /* Guard returns "not indexed" error or "no project loaded"; either is correct */
ASSERT_TRUE(strstr(resp, "total") != NULL || strstr(resp, "not indexed") != NULL ||
strstr(resp, "no project loaded") != NULL);
free(resp);
diff --git a/tests/test_userconfig.c b/tests/test_userconfig.c
index efaf61d19..bc4f8fd45 100644
--- a/tests/test_userconfig.c
+++ b/tests/test_userconfig.c
@@ -71,9 +71,9 @@ TEST(userconfig_global_via_env) {
0);
/* Set env var, load, restore */
- setenv("XDG_CONFIG_HOME", xdg_dir, 1);
+ cbm_setenv("XDG_CONFIG_HOME", xdg_dir, 1);
cbm_userconfig_t *cfg = cbm_userconfig_load(NULL); /* no project dir */
- unsetenv("XDG_CONFIG_HOME");
+ cbm_unsetenv("XDG_CONFIG_HOME");
ASSERT_NOT_NULL(cfg);
ASSERT_EQ(cbm_userconfig_lookup(cfg, ".twig"), CBM_LANG_HTML);
@@ -110,9 +110,9 @@ TEST(userconfig_project_wins_over_global) {
write_json(proj_path, "{\"extra_extensions\":{\".xyz\":\"rust\"}}"),
0);
- setenv("XDG_CONFIG_HOME", xdg_dir, 1);
+ cbm_setenv("XDG_CONFIG_HOME", xdg_dir, 1);
cbm_userconfig_t *cfg = cbm_userconfig_load(proj_dir);
- unsetenv("XDG_CONFIG_HOME");
+ cbm_unsetenv("XDG_CONFIG_HOME");
ASSERT_NOT_NULL(cfg);
/* Project definition (rust) must win */