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(mcp): resolve projects by internal name + filter ghost dbs (#704)

Martin Vogel1d1772a24fbc
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index 5235aaab5..47f107007 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -885,6 +885,22 @@ static const char *project_db_path(const char *project, char *buf, size_t bufsz)
/* ── Store resolution ──────────────────────────────────────────── */
+/* Read the sole INTERNAL project name from a .db file at full_path.
+ * Opens the file query-mode (no create) and succeeds ONLY when the db holds
+ * exactly one project row with a non-empty name — this filters ghost/empty
+ * /corrupt dbs (0-byte file, missing `projects` table, or >1 row). On success
+ * the internal name is copied into name_out; if out_store is non-NULL the open
+ * handle is transferred to the caller (who must cbm_store_close it). On failure
+ * the store is always closed. Defined after is_project_db_file below. */
+static bool db_internal_project_name(const char *full_path, char *name_out, size_t name_sz,
+ cbm_store_t **out_store);
+
+/* #704 fallback: scan the cache dir for the db whose sole internal project name
+ * equals `project`, returning an open store handle (caller owns it) or NULL.
+ * Used only when <project>.db is absent or its internal name differs from the
+ * passed name (drifted filename). Defined after is_project_db_file below. */
+static cbm_store_t *resolve_store_fallback_scan(const char *project);
+
/* Open the right project's .db file for query tools.
* Caches the connection — reopens only when project changes.
* Tracks last-access time so the event loop can evict idle stores. */
@@ -941,12 +957,29 @@ static cbm_store_t *resolve_store(cbm_mcp_server_t *srv, const char *project) {
* 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);
+ if (cbm_store_get_project(srv->store, project, &proj_verify) == CBM_STORE_OK) {
+ cbm_project_free_fields(&proj_verify);
+ srv->owns_store = true;
+ free(srv->current_project);
+ srv->current_project = heap_strdup(project);
+ return srv->store; /* fast path: filename == internal name */
+ }
+ /* #704: <project>.db exists but its INTERNAL project name differs from
+ * the passed name (a copied/renamed db, or a legacy '.'-vs-'-' username
+ * twin). Close it and fall through to the cache-dir scan below. */
+ cbm_store_close(srv->store);
+ srv->store = NULL;
+ }
+
+ /* #704 fallback: either <project>.db is absent or its internal name drifted
+ * from its filename. Node rows are keyed on the INTERNAL name (== the passed
+ * name, since list_projects now advertises internal names), so scan the
+ * cache dir for the db whose sole internal project name equals `project` and
+ * adopt it. Runs ONLY on the fallback — the common fast path is unchanged.
+ * No match → NULL (a genuine typo stays not-found). */
+ cbm_store_t *scanned = resolve_store_fallback_scan(project);
+ if (scanned) {
+ srv->store = scanned;
srv->owns_store = true;
free(srv->current_project);
srv->current_project = heap_strdup(project);
@@ -977,12 +1010,21 @@ static int collect_db_project_names(const char *dir_path, char *out, size_t out_
if (!is_project_db_file(n, len)) {
continue;
}
+ /* #704: advertise the db's INTERNAL project name, not its filename, and
+ * skip ghost/empty/corrupt dbs — so the hint lists names the user can
+ * actually pass to resolve a store. */
+ char full_path[CBM_SZ_2K];
+ snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, n);
+ char iname[CBM_SZ_1K];
+ if (!db_internal_project_name(full_path, iname, sizeof(iname), NULL)) {
+ continue;
+ }
if ((size_t)offset >= out_sz)
break; /* bounds check before write */
if (count > 0 && offset < (int)out_sz - MCP_SEPARATOR) {
out[offset++] = ',';
}
- int wrote = snprintf(out + offset, out_sz - (size_t)offset, "\"%.*s\"", (int)(len - 3), n);
+ int wrote = snprintf(out + offset, out_sz - (size_t)offset, "\"%s\"", iname);
if (wrote > 0) {
offset += wrote;
if ((size_t)offset >= out_sz) {
@@ -1081,34 +1123,96 @@ static bool is_project_db_file(const char *name, size_t len) {
return true;
}
+/* db_internal_project_name — see forward declaration above resolve_store. */
+static bool db_internal_project_name(const char *full_path, char *name_out, size_t name_sz,
+ cbm_store_t **out_store) {
+ if (out_store) {
+ *out_store = NULL;
+ }
+ cbm_store_t *st = cbm_store_open_path_query(full_path);
+ if (!st) {
+ return false; /* nonexistent / unreadable */
+ }
+ cbm_project_t *projs = NULL;
+ int n = 0;
+ bool ok = false;
+ if (cbm_store_list_projects(st, &projs, &n) == CBM_STORE_OK && n == 1 && projs[0].name &&
+ projs[0].name[0]) {
+ snprintf(name_out, name_sz, "%s", projs[0].name);
+ ok = true;
+ }
+ cbm_store_free_projects(projs, n);
+ if (ok && out_store) {
+ *out_store = st; /* transfer ownership to caller */
+ } else {
+ cbm_store_close(st);
+ }
+ return ok;
+}
+
+/* resolve_store_fallback_scan — see forward declaration above resolve_store. */
+static cbm_store_t *resolve_store_fallback_scan(const char *project) {
+ char dir_path[CBM_SZ_1K];
+ cache_dir(dir_path, sizeof(dir_path));
+ cbm_dir_t *d = cbm_opendir(dir_path);
+ if (!d) {
+ return NULL;
+ }
+ cbm_store_t *found = NULL;
+ cbm_dirent_t *entry;
+ while ((entry = cbm_readdir(d)) != NULL) {
+ const char *n = entry->name;
+ size_t len = strlen(n);
+ if (!is_project_db_file(n, len)) {
+ continue;
+ }
+ char full_path[CBM_SZ_2K];
+ snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, n);
+ char iname[CBM_SZ_1K];
+ cbm_store_t *st = NULL;
+ if (db_internal_project_name(full_path, iname, sizeof(iname), &st)) {
+ if (strcmp(iname, project) == 0) {
+ found = st; /* adopt — caller takes ownership */
+ break;
+ }
+ cbm_store_close(st);
+ }
+ }
+ cbm_closedir(d);
+ return found;
+}
+
/* Open a .db file briefly, collect node/edge counts and root_path,
* then append a JSON entry to arr. */
static void build_project_json_entry(yyjson_mut_doc *doc, yyjson_mut_val *arr, const char *dir_path,
const char *name, size_t name_len, int64_t size_bytes) {
- char project_name[CBM_SZ_1K];
- snprintf(project_name, sizeof(project_name), "%.*s", (int)(name_len - 3), name);
+ (void)name_len;
char full_path[CBM_SZ_2K];
snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, name);
- cbm_store_t *pstore = cbm_store_open_path(full_path);
- int nodes = 0;
- int edges = 0;
+ /* #704: key on the db's INTERNAL project name, not its filename. Node/edge
+ * rows are tagged with the internal name, so a drifted filename (copied or
+ * renamed db, legacy '.'-vs-'-' username twin) would otherwise report 0
+ * nodes/edges and be unresolvable. Skip ghost/empty/corrupt dbs entirely so
+ * they don't appear as resolvable projects. */
+ char project_name[CBM_SZ_1K];
+ cbm_store_t *pstore = NULL;
+ if (!db_internal_project_name(full_path, project_name, sizeof(project_name), &pstore)) {
+ return; /* ghost / unreadable — not a resolvable project */
+ }
+
+ int nodes = cbm_store_count_nodes(pstore, project_name);
+ int edges = cbm_store_count_edges(pstore, project_name);
char root_path_buf[CBM_SZ_1K] = "";
- if (pstore) {
- nodes = cbm_store_count_nodes(pstore, project_name);
- edges = cbm_store_count_edges(pstore, project_name);
- cbm_project_t proj = {0};
- if (cbm_store_get_project(pstore, project_name, &proj) == CBM_STORE_OK) {
- if (proj.root_path) {
- snprintf(root_path_buf, sizeof(root_path_buf), "%s", proj.root_path);
- }
- safe_str_free(&proj.name);
- safe_str_free(&proj.indexed_at);
- safe_str_free(&proj.root_path);
+ cbm_project_t proj = {0};
+ if (cbm_store_get_project(pstore, project_name, &proj) == CBM_STORE_OK) {
+ if (proj.root_path) {
+ snprintf(root_path_buf, sizeof(root_path_buf), "%s", proj.root_path);
}
- cbm_store_close(pstore);
+ cbm_project_free_fields(&proj);
}
+ cbm_store_close(pstore);
yyjson_mut_val *p = yyjson_mut_obj(doc);
yyjson_mut_obj_add_strcpy(doc, p, "name", project_name);
diff --git a/tests/test_mcp.c b/tests/test_mcp.c
index 3bfb45c8f..08a266b7d 100644
--- a/tests/test_mcp.c
+++ b/tests/test_mcp.c
@@ -2358,15 +2358,23 @@ TEST(tool_bad_project_name_no_overflow_issue235) {
char *saved_copy = saved ? strdup(saved) : NULL;
cbm_setenv("CBM_CACHE_DIR", cache, 1);
- /* 40 * ~130-char names overflows the 4 KB available-projects buffer. */
+ /* 40 * ~120-char names overflows the 4 KB available-projects buffer.
+ * collect_db_project_names advertises each db's INTERNAL project name
+ * (#704), so the fixture must hold valid dbs with long internal names —
+ * not stub files — for the bounds-check path to actually be exercised. */
enum { ISSUE235_N = 40 };
for (int i = 0; i < ISSUE235_N; i++) {
char name[512];
ISSUE235_DBNAME(name, cache, i);
- FILE *fp = fopen(name, "w");
- if (fp) {
- fputc('x', fp);
- fclose(fp);
+ char iname[256];
+ snprintf(iname, sizeof(iname),
+ "proj_%02d_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ i);
+ cbm_store_t *st = cbm_store_open_path(name);
+ if (st) {
+ cbm_store_upsert_project(st, iname, cache);
+ cbm_store_close(st);
}
}
@@ -2391,12 +2399,186 @@ TEST(tool_bad_project_name_no_overflow_issue235) {
char name[512];
ISSUE235_DBNAME(name, cache, i);
cbm_unlink(name);
+ char side[540];
+ snprintf(side, sizeof(side), "%s-wal", name);
+ cbm_unlink(side);
+ snprintf(side, sizeof(side), "%s-shm", name);
+ cbm_unlink(side);
}
cbm_rmdir(cache);
PASS();
}
#undef ISSUE235_DBNAME
+/* ── #704: project resolution must key on the db's INTERNAL project name ──
+ *
+ * Issue #704: project resolution is registry-less and filename-addressed.
+ * resolve_store() opens <cache>/<passed>.db and then requires the internal
+ * `projects.name` row to equal the passed name; list_projects /
+ * collect_db_project_names derive the advertised name from the .db FILENAME.
+ * When a db's filename != its internal name (a legacy '.'-vs-'-' username
+ * twin, or a copied/renamed file) it shows up in list_projects under the
+ * filename, but every query returns "project not found" — node rows are
+ * tagged with the INTERNAL name, so neither the filename nor the resolve
+ * path lines up. The fix makes list + resolve both key on the INTERNAL name.
+ *
+ * Reproduce-first fixture in an isolated CBM_CACHE_DIR:
+ * - alpha704.db : filename == internal name "alpha704" (control / fast path)
+ * - gamma704.db : internal name "beta704" (DRIFT: built as
+ * beta704.db then renamed → filename != internal name)
+ * - ghost704.db : 0-byte file (ghost / unresolvable)
+ *
+ * RED on buggy code / GREEN on the fix:
+ * A. list_projects advertises "beta704" (internal), NOT "gamma704" (filename),
+ * and NOT "ghost704" (0-byte filtered).
+ * B. search_graph(project="beta704") resolves via the cache-dir scan and
+ * returns the node — not the "project not found" error.
+ * C. control project "alpha704" still resolves on the fast path.
+ * D. the 0-byte ghost is not resolvable.
+ * E. addressing the drifted db by its FILENAME ("gamma704") stays not-found
+ * (we key on the internal name, never the file on disk).
+ */
+
+/* Create a file-backed project db at <dir>/<filename> whose INTERNAL project
+ * name is `internal` (which may differ from the filename), holding one
+ * Function node named `fn`. Returns true on success. */
+static bool issue704_make_db(const char *dir, const char *filename, const char *internal,
+ const char *fn) {
+ char path[700];
+ snprintf(path, sizeof(path), "%s/%s", dir, filename);
+ cbm_store_t *st = cbm_store_open_path(path);
+ if (!st) {
+ return false;
+ }
+ bool ok = (cbm_store_upsert_project(st, internal, dir) == CBM_STORE_OK);
+ if (ok) {
+ char qn[256];
+ snprintf(qn, sizeof(qn), "%s.%s", internal, fn);
+ cbm_node_t n = {0};
+ n.project = internal;
+ n.label = "Function";
+ n.name = fn;
+ n.qualified_name = qn;
+ n.file_path = "main.go";
+ n.start_line = 1;
+ n.end_line = 2;
+ ok = (cbm_store_upsert_node(st, &n) > 0);
+ }
+ cbm_store_close(st);
+ return ok;
+}
+
+TEST(tool_resolve_store_by_internal_name_issue704) {
+ char cache[256];
+ snprintf(cache, sizeof(cache), "/tmp/cbm-issue704-XXXXXX");
+ if (!cbm_mkdtemp(cache)) {
+ PASS(); /* skip if mkdtemp fails — not a #704 signal */
+ }
+
+ const char *saved = getenv("CBM_CACHE_DIR");
+ char *saved_copy = saved ? strdup(saved) : NULL;
+ cbm_setenv("CBM_CACHE_DIR", cache, 1);
+
+ /* (1) control: filename == internal name */
+ ASSERT_TRUE(issue704_make_db(cache, "alpha704.db", "alpha704", "alphaFunc704"));
+
+ /* (2) DRIFT: build beta704.db (internal "beta704") then rename the file to
+ * gamma704.db, so filename "gamma704" != internal "beta704". */
+ ASSERT_TRUE(issue704_make_db(cache, "beta704.db", "beta704", "betaFunc704"));
+ char beta_path[700];
+ char gamma_path[700];
+ snprintf(beta_path, sizeof(beta_path), "%s/beta704.db", cache);
+ snprintf(gamma_path, sizeof(gamma_path), "%s/gamma704.db", cache);
+ ASSERT_EQ(rename(beta_path, gamma_path), 0);
+
+ /* (3) ghost: 0-byte db file */
+ char ghost_path[700];
+ snprintf(ghost_path, sizeof(ghost_path), "%s/ghost704.db", cache);
+ FILE *gp = fopen(ghost_path, "w");
+ ASSERT_NOT_NULL(gp);
+ fclose(gp);
+
+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
+ ASSERT_NOT_NULL(srv);
+
+ /* ── A: list_projects reports INTERNAL names; filters the ghost ── */
+ char *list =
+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\","
+ "\"params\":{\"name\":\"list_projects\",\"arguments\":{}}}");
+ ASSERT_NOT_NULL(list);
+ ASSERT_NOT_NULL(strstr(list, "alpha704")); /* control */
+ ASSERT_NOT_NULL(strstr(list, "beta704")); /* internal name of drifted db (RED before) */
+ ASSERT_NULL(strstr(list, "gamma704")); /* filename must NOT be advertised (RED before) */
+ ASSERT_NULL(strstr(list, "ghost704")); /* 0-byte ghost filtered (RED before) */
+ free(list);
+
+ /* ── B: the drifted project resolves by its INTERNAL name ──────── */
+ char *q_beta = cbm_mcp_server_handle(
+ srv, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\","
+ "\"params\":{\"name\":\"search_graph\",\"arguments\":{"
+ "\"project\":\"beta704\",\"name_pattern\":\"betaFunc704\",\"limit\":5}}}");
+ ASSERT_NOT_NULL(q_beta);
+ ASSERT_NOT_NULL(strstr(q_beta, "betaFunc704")); /* resolved + returned node (RED before) */
+ ASSERT_NULL(strstr(q_beta, "not found")); /* not the not-found error */
+ free(q_beta);
+
+ /* ── C: control project still resolves on the fast path ────────── */
+ char *q_alpha = cbm_mcp_server_handle(
+ srv, "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\","
+ "\"params\":{\"name\":\"search_graph\",\"arguments\":{"
+ "\"project\":\"alpha704\",\"name_pattern\":\"alphaFunc704\",\"limit\":5}}}");
+ ASSERT_NOT_NULL(q_alpha);
+ ASSERT_NOT_NULL(strstr(q_alpha, "alphaFunc704"));
+ free(q_alpha);
+
+ /* ── D: the 0-byte ghost is NOT resolvable ─────────────────────── */
+ char *q_ghost = cbm_mcp_server_handle(
+ srv, "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/call\","
+ "\"params\":{\"name\":\"search_graph\",\"arguments\":{"
+ "\"project\":\"ghost704\",\"name_pattern\":\".*\",\"limit\":5}}}");
+ ASSERT_NOT_NULL(q_ghost);
+ ASSERT_NOT_NULL(strstr(q_ghost, "not found"));
+ free(q_ghost);
+
+ /* ── E: addressing the drifted db by its FILENAME stays not-found ── */
+ char *q_gamma = cbm_mcp_server_handle(
+ srv, "{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/call\","
+ "\"params\":{\"name\":\"search_graph\",\"arguments\":{"
+ "\"project\":\"gamma704\",\"name_pattern\":\".*\",\"limit\":5}}}");
+ ASSERT_NOT_NULL(q_gamma);
+ ASSERT_NOT_NULL(strstr(q_gamma, "not found"));
+ free(q_gamma);
+
+ cbm_mcp_server_free(srv);
+
+ /* ── cleanup ───────────────────────────────────────────────────── */
+ if (saved_copy) {
+ cbm_setenv("CBM_CACHE_DIR", saved_copy, 1);
+ free(saved_copy);
+ } else {
+ cbm_unsetenv("CBM_CACHE_DIR");
+ }
+ char a_path[700];
+ snprintf(a_path, sizeof(a_path), "%s/alpha704.db", cache);
+ char corrupt_path[720];
+ snprintf(corrupt_path, sizeof(corrupt_path), "%s.corrupt", ghost_path);
+ cbm_unlink(a_path);
+ cbm_unlink(gamma_path);
+ cbm_unlink(ghost_path);
+ cbm_unlink(corrupt_path); /* ghost may be quarantined by resolve_store */
+ char side[740];
+ snprintf(side, sizeof(side), "%s-wal", a_path);
+ cbm_unlink(side);
+ snprintf(side, sizeof(side), "%s-shm", a_path);
+ cbm_unlink(side);
+ snprintf(side, sizeof(side), "%s-wal", gamma_path);
+ cbm_unlink(side);
+ snprintf(side, sizeof(side), "%s-shm", gamma_path);
+ cbm_unlink(side);
+ cbm_rmdir(cache);
+ PASS();
+}
+
/* ══════════════════════════════════════════════════════════════════
* SUITE
* ══════════════════════════════════════════════════════════════════ */
@@ -2548,4 +2730,5 @@ SUITE(mcp) {
RUN_TEST(snippet_include_neighbors_enabled);
RUN_TEST(snippet_source_invalid_utf8);
RUN_TEST(tool_bad_project_name_no_overflow_issue235);
+ RUN_TEST(tool_resolve_store_by_internal_name_issue704);
}