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.

feat(mcp): add bounded graph comparison tool

Martin Vogelcf6e62043195
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index 0ce6ae7eb..616bbf6a1 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -1,5 +1,5 @@
/*
- * mcp.c — MCP server: JSON-RPC 2.0 over stdio with 14 graph tools.
+ * mcp.c — MCP server: JSON-RPC 2.0 over stdio with graph tools.
*
* Uses yyjson for fast JSON parsing/building.
* Single-threaded event loop: read line → parse → dispatch → respond.
@@ -36,6 +36,11 @@ enum {
MCP_TOOLS_PAGE_SIZE = 8,
MCP_HELP_TOOLS_WRAP_COL = 74, /* --help tool list stays readable on 80-col terminals */
MCP_MAX_CROSS_REPO_TARGETS = 4096,
+ MCP_COMPARE_DEFAULT_LIMIT = 200,
+ MCP_COMPARE_MAX_LIMIT = 1000,
+ MCP_COMPARE_DEFAULT_SCAN_LIMIT = 2000000,
+ MCP_COMPARE_MAX_SCAN_LIMIT = 10000000,
+ MCP_COMPARE_SET_BYTE_BUDGET = 512 * 1024,
};
#define MCP_MS_TO_US 1000LL
#define MCP_S_TO_US 1000000LL
@@ -556,6 +561,19 @@ static const tool_def_t TOOLS[] = {
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":["
"\"project\"]}"},
+ {"compare_graphs", "Compare graphs",
+ "Compare two indexed project snapshots. Returns deterministic target-only additions and "
+ "base-only removals for stable node and edge identities using a bounded streaming merge. "
+ "Each result set is independently capped by limit and a fixed 512 KiB encoded-byte budget; "
+ "exact totals and truncation reasons are always reported.",
+ "{\"type\":\"object\",\"properties\":{"
+ "\"base_project\":{\"type\":\"string\",\"minLength\":1},"
+ "\"target_project\":{\"type\":\"string\",\"minLength\":1},"
+ "\"limit\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":1000,\"default\":200},"
+ "\"scan_limit\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":10000000,"
+ "\"default\":2000000}},\"required\":[\"base_project\",\"target_project\"],"
+ "\"additionalProperties\":false}"},
+
{"get_architecture", "Get architecture",
"Get high-level architecture overview. DEFAULT (no aspects) is a compact summary — "
"overview counts, languages, packages, entry_points; request more via aspects:[...] "
@@ -719,6 +737,7 @@ static const tool_annotation_def_t TOOL_ANNOTATIONS[] = {
{"trace_path", false, true, true, false},
{"get_code_snippet", false, true, true, false},
{"get_graph_schema", false, true, true, false},
+ {"compare_graphs", true, false, true, false},
{"get_architecture", false, true, true, false},
{"search_code", false, true, true, false},
{"list_projects", true, false, true, false},
@@ -780,9 +799,9 @@ static void mcp_add_tool_def(yyjson_mut_doc *doc, yyjson_mut_val *tools, int i)
static bool mcp_tool_allowed(cbm_mcp_tool_profile_t profile, const char *name) {
static const char *const analysis_tools[] = {
- "search_graph", "query_graph", "trace_path", "get_code_snippet",
- "get_graph_schema", "get_architecture", "search_code", "list_projects",
- "index_status", "check_index_coverage", "detect_changes",
+ "search_graph", "query_graph", "trace_path", "get_code_snippet",
+ "get_graph_schema", "compare_graphs", "get_architecture", "search_code",
+ "list_projects", "index_status", "check_index_coverage", "detect_changes",
};
static const char *const scout_tools[] = {
"search_graph", "trace_path", "get_code_snippet", "get_architecture",
@@ -2751,6 +2770,407 @@ static char *verify_project_indexed(cbm_store_t *store, const char *project) {
return NULL;
}
+/* compare_graphs deliberately bypasses resolve_store(): it needs two
+ * independently-owned request-scoped read handles, while resolve_store caches
+ * one handle on the server. Direct-name lookup stays the fast path; the
+ * existing internal-name fallback preserves legacy renamed databases. */
+static cbm_store_t *compare_open_project_store(const char *project) {
+ char path[CBM_SZ_1K];
+ project_db_path(project, path, sizeof(path));
+ cbm_store_t *store = path[0] ? cbm_store_open_path_query(path) : NULL;
+ if (store) {
+ cbm_project_t row = {0};
+ if (cbm_store_get_project(store, project, &row) == CBM_STORE_OK) {
+ cbm_project_free_fields(&row);
+ return store;
+ }
+ cbm_store_close(store);
+ }
+ return resolve_store_fallback_scan(project);
+}
+
+typedef struct {
+ yyjson_mut_val *items;
+ size_t returned;
+ size_t encoded_bytes;
+ bool budget_exhausted;
+} compare_result_set_t;
+
+typedef struct {
+ cbm_mcp_server_t *server;
+ yyjson_mut_doc *doc;
+ size_t limit;
+ compare_result_set_t nodes_added;
+ compare_result_set_t nodes_removed;
+ compare_result_set_t edges_added;
+ compare_result_set_t edges_removed;
+} compare_response_t;
+
+static char *compare_graphs_error(const char *code, const char *message) {
+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
+ yyjson_mut_val *root = doc ? yyjson_mut_obj(doc) : NULL;
+ if (!doc || !root) {
+ yyjson_mut_doc_free(doc);
+ return cbm_mcp_text_result("compare_graphs failed: out of memory", true);
+ }
+ yyjson_mut_doc_set_root(doc, root);
+ if (!yyjson_mut_obj_add_strcpy(doc, root, "error", message) ||
+ !yyjson_mut_obj_add_strcpy(doc, root, "code", code)) {
+ yyjson_mut_doc_free(doc);
+ return cbm_mcp_text_result("compare_graphs failed: out of memory", true);
+ }
+ char *json = yy_doc_to_str(doc);
+ yyjson_mut_doc_free(doc);
+ if (!json) {
+ return cbm_mcp_text_result("compare_graphs failed: out of memory", true);
+ }
+ char *result = cbm_mcp_text_result(json, true);
+ free(json);
+ return result;
+}
+
+static bool compare_arg_name_allowed(const char *name) {
+ return strcmp(name, "base_project") == 0 || strcmp(name, "target_project") == 0 ||
+ strcmp(name, "limit") == 0 || strcmp(name, "scan_limit") == 0;
+}
+
+static bool compare_parse_bounded_integer(yyjson_val *root, const char *key, int64_t default_value,
+ int64_t maximum, uint64_t *out,
+ const char **error_message) {
+ yyjson_val *value = yyjson_obj_get(root, key);
+ int64_t parsed = default_value;
+ if (value) {
+ if (!yyjson_is_int(value)) {
+ *error_message = "limit values must be integers";
+ return false;
+ }
+ parsed = yyjson_get_int(value);
+ }
+ if (parsed < 1 || parsed > maximum) {
+ *error_message = strcmp(key, "limit") == 0 ? "limit must be between 1 and 1000"
+ : "scan_limit must be between 1 and 10000000";
+ return false;
+ }
+ *out = (uint64_t)parsed;
+ return true;
+}
+
+static bool compare_parse_arguments(const char *args, char **base_project, char **target_project,
+ uint64_t *limit, uint64_t *scan_limit,
+ const char **error_message) {
+ *base_project = NULL;
+ *target_project = NULL;
+ yyjson_doc *doc = yyjson_read(args ? args : "{}", args ? strlen(args) : SLEN("{}"), 0);
+ if (!doc) {
+ *error_message = "arguments must be valid JSON";
+ return false;
+ }
+ yyjson_val *root = yyjson_doc_get_root(doc);
+ if (!yyjson_is_obj(root)) {
+ *error_message = "arguments must be an object";
+ yyjson_doc_free(doc);
+ return false;
+ }
+
+ yyjson_obj_iter iterator = yyjson_obj_iter_with(root);
+ yyjson_val *key = NULL;
+ while ((key = yyjson_obj_iter_next(&iterator)) != NULL) {
+ const char *name = yyjson_get_str(key);
+ if (!name || !compare_arg_name_allowed(name)) {
+ *error_message = "unknown argument";
+ yyjson_doc_free(doc);
+ return false;
+ }
+ }
+
+ yyjson_val *base = yyjson_obj_get(root, "base_project");
+ yyjson_val *target = yyjson_obj_get(root, "target_project");
+ if (!base || !yyjson_is_str(base) || yyjson_get_len(base) == 0 || !target ||
+ !yyjson_is_str(target) || yyjson_get_len(target) == 0) {
+ *error_message = "base_project and target_project are required non-empty strings";
+ yyjson_doc_free(doc);
+ return false;
+ }
+ if (strcmp(yyjson_get_str(base), yyjson_get_str(target)) == 0) {
+ *error_message = "base_project and target_project must be distinct";
+ yyjson_doc_free(doc);
+ return false;
+ }
+ if (!compare_parse_bounded_integer(root, "limit", MCP_COMPARE_DEFAULT_LIMIT,
+ MCP_COMPARE_MAX_LIMIT, limit, error_message) ||
+ !compare_parse_bounded_integer(root, "scan_limit", MCP_COMPARE_DEFAULT_SCAN_LIMIT,
+ MCP_COMPARE_MAX_SCAN_LIMIT, scan_limit, error_message)) {
+ yyjson_doc_free(doc);
+ return false;
+ }
+
+ *base_project = heap_strdup(yyjson_get_str(base));
+ *target_project = heap_strdup(yyjson_get_str(target));
+ yyjson_doc_free(doc);
+ if (!*base_project || !*target_project) {
+ free(*base_project);
+ free(*target_project);
+ *base_project = NULL;
+ *target_project = NULL;
+ *error_message = "out of memory while validating arguments";
+ return false;
+ }
+ return true;
+}
+
+static yyjson_mut_val *compare_node_json(yyjson_mut_doc *doc,
+ const cbm_graph_node_identity_t *node) {
+ yyjson_mut_val *object = yyjson_mut_obj(doc);
+ if (!object ||
+ !yyjson_mut_obj_add_strcpy(doc, object, "qualified_name", node->qualified_name) ||
+ !yyjson_mut_obj_add_strcpy(doc, object, "label", node->label) ||
+ !yyjson_mut_obj_add_strcpy(doc, object, "file_path", node->file_path)) {
+ return NULL;
+ }
+ return object;
+}
+
+static bool compare_append_item(compare_response_t *response, compare_result_set_t *set,
+ yyjson_mut_doc *item_doc, yyjson_mut_val *item) {
+ if (!item_doc || !item) {
+ yyjson_mut_doc_free(item_doc);
+ return false;
+ }
+ char *encoded = yy_doc_to_str(item_doc);
+ if (!encoded) {
+ yyjson_mut_doc_free(item_doc);
+ return false;
+ }
+ size_t encoded_len = strlen(encoded);
+ size_t separator = set->returned > 0 ? 1U : 0U;
+ free(encoded);
+
+ if (set->encoded_bytes > MCP_COMPARE_SET_BYTE_BUDGET ||
+ separator > MCP_COMPARE_SET_BYTE_BUDGET - set->encoded_bytes ||
+ encoded_len > MCP_COMPARE_SET_BYTE_BUDGET - set->encoded_bytes - separator) {
+ set->budget_exhausted = true;
+ yyjson_mut_doc_free(item_doc);
+ return true;
+ }
+
+ yyjson_mut_val *copy = yyjson_mut_val_mut_copy(response->doc, item);
+ bool ok = copy && yyjson_mut_arr_add_val(set->items, copy);
+ yyjson_mut_doc_free(item_doc);
+ if (!ok) {
+ return false;
+ }
+ set->encoded_bytes += separator + encoded_len;
+ set->returned++;
+ return true;
+}
+
+static bool compare_node_callback(void *context, bool added,
+ const cbm_graph_node_identity_t *node) {
+ compare_response_t *response = (compare_response_t *)context;
+ compare_result_set_t *set = added ? &response->nodes_added : &response->nodes_removed;
+ if (set->returned >= response->limit || set->budget_exhausted) {
+ return true;
+ }
+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
+ yyjson_mut_val *item = doc ? compare_node_json(doc, node) : NULL;
+ if (doc && item) {
+ yyjson_mut_doc_set_root(doc, item);
+ }
+ return compare_append_item(response, set, doc, item);
+}
+
+static bool compare_edge_callback(void *context, bool added,
+ const cbm_graph_edge_identity_t *edge) {
+ compare_response_t *response = (compare_response_t *)context;
+ compare_result_set_t *set = added ? &response->edges_added : &response->edges_removed;
+ if (set->returned >= response->limit || set->budget_exhausted) {
+ return true;
+ }
+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
+ yyjson_mut_val *item = doc ? yyjson_mut_obj(doc) : NULL;
+ yyjson_mut_val *source = doc ? compare_node_json(doc, &edge->source) : NULL;
+ yyjson_mut_val *target = doc ? compare_node_json(doc, &edge->target) : NULL;
+ bool ok = item && source && target && yyjson_mut_obj_add_val(doc, item, "source", source) &&
+ yyjson_mut_obj_add_val(doc, item, "target", target) &&
+ yyjson_mut_obj_add_strcpy(doc, item, "type", edge->type) &&
+ yyjson_mut_obj_add_strcpy(doc, item, "local_name_gen", edge->local_name_gen);
+ if (ok) {
+ yyjson_mut_doc_set_root(doc, item);
+ }
+ return compare_append_item(response, set, doc, ok ? item : NULL);
+}
+
+static bool compare_cancel_callback(void *context) {
+ compare_response_t *response = (compare_response_t *)context;
+ return mcp_request_cancelled(response->server);
+}
+
+static yyjson_mut_val *compare_project_json(yyjson_mut_doc *doc, const char *project,
+ const cbm_graph_compare_project_t *metadata) {
+ yyjson_mut_val *object = yyjson_mut_obj(doc);
+ if (!object || !yyjson_mut_obj_add_strcpy(doc, object, "project", project) ||
+ !yyjson_mut_obj_add_strcpy(doc, object, "generation", metadata->generation) ||
+ !yyjson_mut_obj_add_strcpy(doc, object, "index_mode", metadata->index_mode) ||
+ !yyjson_mut_obj_add_sint(doc, object, "node_count", metadata->node_count) ||
+ !yyjson_mut_obj_add_sint(doc, object, "edge_count", metadata->edge_count)) {
+ return NULL;
+ }
+ return object;
+}
+
+static yyjson_mut_val *compare_set_json(yyjson_mut_doc *doc, compare_result_set_t *set,
+ uint64_t total, size_t limit) {
+ yyjson_mut_val *object = yyjson_mut_obj(doc);
+ yyjson_mut_val *reasons = yyjson_mut_arr(doc);
+ bool truncated = total > (uint64_t)set->returned;
+ if (!object || !reasons || !yyjson_mut_obj_add_val(doc, object, "items", set->items) ||
+ !yyjson_mut_obj_add_uint(doc, object, "returned", set->returned) ||
+ !yyjson_mut_obj_add_uint(doc, object, "total", total) ||
+ !yyjson_mut_obj_add_bool(doc, object, "truncated", truncated)) {
+ return NULL;
+ }
+ if (truncated && set->returned >= limit && !yyjson_mut_arr_add_strcpy(doc, reasons, "limit")) {
+ return NULL;
+ }
+ if (truncated && set->budget_exhausted &&
+ !yyjson_mut_arr_add_strcpy(doc, reasons, "encoded_byte_budget")) {
+ return NULL;
+ }
+ if (!yyjson_mut_obj_add_val(doc, object, "truncation_reasons", reasons)) {
+ return NULL;
+ }
+ return object;
+}
+
+static char *handle_compare_graphs(cbm_mcp_server_t *server, const char *args) {
+ char *base_project = NULL;
+ char *target_project = NULL;
+ uint64_t limit = 0;
+ uint64_t scan_limit = 0;
+ const char *argument_error = NULL;
+ if (!compare_parse_arguments(args, &base_project, &target_project, &limit, &scan_limit,
+ &argument_error)) {
+ return compare_graphs_error("invalid_arguments", argument_error);
+ }
+ if (mcp_request_cancelled(server)) {
+ free(base_project);
+ free(target_project);
+ return compare_graphs_error("cancelled", "compare_graphs cancelled for this request");
+ }
+
+ cbm_store_t *base_store = compare_open_project_store(base_project);
+ if (!base_store) {
+ free(base_project);
+ free(target_project);
+ return compare_graphs_error("project_not_indexed", "base project is not indexed");
+ }
+ cbm_store_t *target_store = compare_open_project_store(target_project);
+ if (!target_store) {
+ cbm_store_close(base_store);
+ free(base_project);
+ free(target_project);
+ return compare_graphs_error("project_not_indexed", "target project is not indexed");
+ }
+
+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
+ yyjson_mut_val *root = doc ? yyjson_mut_obj(doc) : NULL;
+ compare_response_t response = {
+ .server = server,
+ .doc = doc,
+ .limit = (size_t)limit,
+ .nodes_added = {.items = doc ? yyjson_mut_arr(doc) : NULL, .encoded_bytes = 2U},
+ .nodes_removed = {.items = doc ? yyjson_mut_arr(doc) : NULL, .encoded_bytes = 2U},
+ .edges_added = {.items = doc ? yyjson_mut_arr(doc) : NULL, .encoded_bytes = 2U},
+ .edges_removed = {.items = doc ? yyjson_mut_arr(doc) : NULL, .encoded_bytes = 2U},
+ };
+ if (!doc || !root || !response.nodes_added.items || !response.nodes_removed.items ||
+ !response.edges_added.items || !response.edges_removed.items) {
+ cbm_store_close(target_store);
+ cbm_store_close(base_store);
+ yyjson_mut_doc_free(doc);
+ free(base_project);
+ free(target_project);
+ return compare_graphs_error("allocation_failed", "could not allocate comparison result");
+ }
+ yyjson_mut_doc_set_root(doc, root);
+
+ cbm_graph_compare_result_t comparison = {0};
+ int compare_rc = cbm_store_compare_graphs(
+ base_store, base_project, target_store, target_project, scan_limit, compare_cancel_callback,
+ compare_node_callback, compare_edge_callback, &response, &comparison);
+ cbm_store_close(target_store);
+ cbm_store_close(base_store);
+
+ if (compare_rc != CBM_STORE_OK) {
+ yyjson_mut_doc_free(doc);
+ free(base_project);
+ free(target_project);
+ if (compare_rc == CBM_STORE_CANCELLED) {
+ return compare_graphs_error("cancelled", "compare_graphs cancelled for this request");
+ }
+ if (compare_rc == CBM_STORE_NOT_FOUND) {
+ return compare_graphs_error("project_not_indexed", "project is not indexed");
+ }
+ if (compare_rc == CBM_STORE_SCAN_LIMIT) {
+ return compare_graphs_error("scan_limit_exceeded",
+ "combined graph rows exceed scan_limit");
+ }
+ if (compare_rc == CBM_STORE_CALLBACK_ERR) {
+ return compare_graphs_error("allocation_failed",
+ "could not allocate comparison result");
+ }
+ return compare_graphs_error("query_failed", "graph comparison query failed");
+ }
+
+ yyjson_mut_val *base = compare_project_json(doc, base_project, &comparison.base);
+ yyjson_mut_val *target = compare_project_json(doc, target_project, &comparison.target);
+ yyjson_mut_val *nodes = yyjson_mut_obj(doc);
+ yyjson_mut_val *edges = yyjson_mut_obj(doc);
+ yyjson_mut_val *limits = yyjson_mut_obj(doc);
+ yyjson_mut_val *nodes_added =
+ compare_set_json(doc, &response.nodes_added, comparison.nodes_added_total, response.limit);
+ yyjson_mut_val *nodes_removed = compare_set_json(
+ doc, &response.nodes_removed, comparison.nodes_removed_total, response.limit);
+ yyjson_mut_val *edges_added =
+ compare_set_json(doc, &response.edges_added, comparison.edges_added_total, response.limit);
+ yyjson_mut_val *edges_removed = compare_set_json(
+ doc, &response.edges_removed, comparison.edges_removed_total, response.limit);
+ bool built =
+ base && target && nodes && edges && limits && nodes_added && nodes_removed && edges_added &&
+ edges_removed && yyjson_mut_obj_add_int(doc, root, "schema_version", 1) &&
+ yyjson_mut_obj_add_val(doc, root, "base", base) &&
+ yyjson_mut_obj_add_val(doc, root, "target", target) &&
+ yyjson_mut_obj_add_val(doc, nodes, "added", nodes_added) &&
+ yyjson_mut_obj_add_val(doc, nodes, "removed", nodes_removed) &&
+ yyjson_mut_obj_add_val(doc, root, "nodes", nodes) &&
+ yyjson_mut_obj_add_val(doc, edges, "added", edges_added) &&
+ yyjson_mut_obj_add_val(doc, edges, "removed", edges_removed) &&
+ yyjson_mut_obj_add_val(doc, root, "edges", edges) &&
+ yyjson_mut_obj_add_uint(doc, limits, "limit", limit) &&
+ yyjson_mut_obj_add_uint(doc, limits, "scan_limit", scan_limit) &&
+ yyjson_mut_obj_add_uint(doc, limits, "encoded_byte_budget", MCP_COMPARE_SET_BYTE_BUDGET) &&
+ yyjson_mut_obj_add_val(doc, root, "limits", limits);
+ free(base_project);
+ free(target_project);
+ if (!built) {
+ yyjson_mut_doc_free(doc);
+ return compare_graphs_error("allocation_failed", "could not allocate comparison result");
+ }
+ if (mcp_request_cancelled(server)) {
+ yyjson_mut_doc_free(doc);
+ return compare_graphs_error("cancelled", "compare_graphs cancelled for this request");
+ }
+
+ char *json = yy_doc_to_str(doc);
+ yyjson_mut_doc_free(doc);
+ if (!json) {
+ return compare_graphs_error("allocation_failed", "could not serialize comparison result");
+ }
+ char *result = cbm_mcp_text_result(json, false);
+ free(json);
+ return result;
+}
+
static bool sg_field_blocked(const char *f); /* internal-only fields, defined with search_graph */
static char *handle_get_graph_schema(cbm_mcp_server_t *srv, const char *args) {
@@ -11413,6 +11833,9 @@ static char *dispatch_tool(cbm_mcp_server_t *srv, const char *tool_name, const c
if (strcmp(tool_name, "get_graph_schema") == 0) {
return handle_get_graph_schema(srv, args_json);
}
+ if (strcmp(tool_name, "compare_graphs") == 0) {
+ return handle_compare_graphs(srv, args_json);
+ }
if (strcmp(tool_name, "search_graph") == 0) {
return handle_search_graph(srv, args_json);
}
diff --git a/src/store/store.c b/src/store/store.c
index ad0b7967b..0f2a5ead6 100644
--- a/src/store/store.c
+++ b/src/store/store.c
@@ -1208,6 +1208,390 @@ int cbm_store_rollback(cbm_store_t *s) {
return exec_sql(s, "ROLLBACK;");
}
+/* ── Graph comparison ────────────────────────────────────────────── */
+
+typedef struct {
+ cbm_graph_compare_cancel_fn cancel;
+ void *context;
+} graph_compare_progress_t;
+
+typedef struct {
+ sqlite3_stmt *stmt;
+ cbm_graph_node_identity_t identity;
+ bool has_row;
+} graph_node_cursor_t;
+
+typedef struct {
+ sqlite3_stmt *stmt;
+ cbm_graph_edge_identity_t identity;
+ bool has_row;
+} graph_edge_cursor_t;
+
+static bool graph_compare_is_cancelled(const graph_compare_progress_t *progress) {
+ return progress && progress->cancel && progress->cancel(progress->context);
+}
+
+static int graph_compare_progress(void *context) {
+ return graph_compare_is_cancelled((const graph_compare_progress_t *)context) ? 1 : 0;
+}
+
+/* SQLite's BINARY collation compares the unsigned bytes of the UTF-8 text.
+ * Keep the merge comparator byte-for-byte equivalent so neither cursor can
+ * be advanced past a row that SQLite considers distinct. */
+static int graph_binary_compare(const char *left, const char *right) {
+ const unsigned char *a = (const unsigned char *)safe_str(left);
+ const unsigned char *b = (const unsigned char *)safe_str(right);
+ while (*a && *a == *b) {
+ a++;
+ b++;
+ }
+ return (*a > *b) - (*a < *b);
+}
+
+static int graph_node_compare(const cbm_graph_node_identity_t *left,
+ const cbm_graph_node_identity_t *right) {
+ int cmp = graph_binary_compare(left->qualified_name, right->qualified_name);
+ if (cmp == 0) {
+ cmp = graph_binary_compare(left->label, right->label);
+ }
+ if (cmp == 0) {
+ cmp = graph_binary_compare(left->file_path, right->file_path);
+ }
+ return cmp;
+}
+
+static int graph_edge_compare(const cbm_graph_edge_identity_t *left,
+ const cbm_graph_edge_identity_t *right) {
+ int cmp = graph_node_compare(&left->source, &right->source);
+ if (cmp == 0) {
+ cmp = graph_node_compare(&left->target, &right->target);
+ }
+ if (cmp == 0) {
+ cmp = graph_binary_compare(left->type, right->type);
+ }
+ if (cmp == 0) {
+ cmp = graph_binary_compare(left->local_name_gen, right->local_name_gen);
+ }
+ return cmp;
+}
+
+static int graph_count_rows(cbm_store_t *store, const char *sql, const char *project,
+ int64_t *out) {
+ sqlite3_stmt *stmt = NULL;
+ if (sqlite3_prepare_v2(store->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
+ store_set_error_sqlite(store, "compare count prepare");
+ return CBM_STORE_ERR;
+ }
+ bind_text(stmt, SKIP_ONE, project);
+ int step_rc = sqlite3_step(stmt);
+ if (step_rc != SQLITE_ROW) {
+ store_set_error_sqlite(store, "compare count");
+ sqlite3_finalize(stmt);
+ return step_rc == SQLITE_INTERRUPT ? CBM_STORE_CANCELLED : CBM_STORE_ERR;
+ }
+ *out = sqlite3_column_int64(stmt, 0);
+ step_rc = sqlite3_step(stmt);
+ sqlite3_finalize(stmt);
+ if (step_rc != SQLITE_DONE) {
+ store_set_error_sqlite(store, "compare count finish");
+ return step_rc == SQLITE_INTERRUPT ? CBM_STORE_CANCELLED : CBM_STORE_ERR;
+ }
+ return CBM_STORE_OK;
+}
+
+static int graph_capture_project(cbm_store_t *store, const char *project,
+ cbm_graph_compare_project_t *out) {
+ cbm_project_t row = {0};
+ int rc = cbm_store_get_project(store, project, &row);
+ if (rc != CBM_STORE_OK) {
+ return rc;
+ }
+ if (!row.name || !row.indexed_at || !row.root_path) {
+ cbm_project_free_fields(&row);
+ store_set_error(store, "compare project allocation failed");
+ return CBM_STORE_ERR;
+ }
+
+ snprintf(out->generation, sizeof(out->generation), "%s", safe_str(row.indexed_at));
+ snprintf(out->index_mode, sizeof(out->index_mode), "unknown");
+
+ cbm_coverage_meta_t meta = {0};
+ rc = cbm_store_coverage_meta_get(store, project, &meta);
+ if (rc == CBM_STORE_OK) {
+ snprintf(out->generation, sizeof(out->generation), "%s", safe_str(meta.generation));
+ snprintf(out->index_mode, sizeof(out->index_mode), "%s", safe_str(meta.index_mode));
+ cbm_store_coverage_meta_clear(&meta);
+ } else if (rc != CBM_STORE_NOT_FOUND) {
+ cbm_project_free_fields(&row);
+ return rc;
+ }
+ cbm_project_free_fields(&row);
+
+ rc = graph_count_rows(store, "SELECT count(*) FROM nodes WHERE project=?1;", project,
+ &out->node_count);
+ if (rc != CBM_STORE_OK) {
+ return rc;
+ }
+ return graph_count_rows(store, "SELECT count(*) FROM edges WHERE project=?1;", project,
+ &out->edge_count);
+}
+
+static int graph_node_cursor_step(cbm_store_t *store, graph_node_cursor_t *cursor) {
+ int rc = sqlite3_step(cursor->stmt);
+ if (rc == SQLITE_DONE) {
+ cursor->has_row = false;
+ return CBM_STORE_OK;
+ }
+ if (rc != SQLITE_ROW) {
+ store_set_error_sqlite(store, "compare node scan");
+ cursor->has_row = false;
+ return rc == SQLITE_INTERRUPT ? CBM_STORE_CANCELLED : CBM_STORE_ERR;
+ }
+ cursor->identity.qualified_name = safe_str((const char *)sqlite3_column_text(cursor->stmt, 0));
+ cursor->identity.label = safe_str((const char *)sqlite3_column_text(cursor->stmt, ST_COL_1));
+ cursor->identity.file_path =
+ safe_str((const char *)sqlite3_column_text(cursor->stmt, ST_COL_2));
+ cursor->has_row = true;
+ return CBM_STORE_OK;
+}
+
+static int graph_edge_cursor_step(cbm_store_t *store, graph_edge_cursor_t *cursor) {
+ int rc = sqlite3_step(cursor->stmt);
+ if (rc == SQLITE_DONE) {
+ cursor->has_row = false;
+ return CBM_STORE_OK;
+ }
+ if (rc != SQLITE_ROW) {
+ store_set_error_sqlite(store, "compare edge scan");
+ cursor->has_row = false;
+ return rc == SQLITE_INTERRUPT ? CBM_STORE_CANCELLED : CBM_STORE_ERR;
+ }
+ cursor->identity.source.qualified_name =
+ safe_str((const char *)sqlite3_column_text(cursor->stmt, 0));
+ cursor->identity.source.label =
+ safe_str((const char *)sqlite3_column_text(cursor->stmt, ST_COL_1));
+ cursor->identity.source.file_path =
+ safe_str((const char *)sqlite3_column_text(cursor->stmt, ST_COL_2));
+ cursor->identity.target.qualified_name =
+ safe_str((const char *)sqlite3_column_text(cursor->stmt, ST_COL_3));
+ cursor->identity.target.label =
+ safe_str((const char *)sqlite3_column_text(cursor->stmt, ST_COL_4));
+ cursor->identity.target.file_path =
+ safe_str((const char *)sqlite3_column_text(cursor->stmt, ST_COL_5));
+ cursor->identity.type = safe_str((const char *)sqlite3_column_text(cursor->stmt, ST_COL_6));
+ cursor->identity.local_name_gen =
+ safe_str((const char *)sqlite3_column_text(cursor->stmt, ST_COL_7));
+ cursor->has_row = true;
+ return CBM_STORE_OK;
+}
+
+static int graph_prepare_node_cursor(cbm_store_t *store, const char *project,
+ graph_node_cursor_t *cursor) {
+ static const char sql[] =
+ "SELECT qualified_name,label,coalesce(file_path,'') FROM nodes WHERE project=?1 "
+ "ORDER BY qualified_name COLLATE BINARY,label COLLATE BINARY,"
+ "coalesce(file_path,'') COLLATE BINARY;";
+ if (sqlite3_prepare_v2(store->db, sql, CBM_NOT_FOUND, &cursor->stmt, NULL) != SQLITE_OK) {
+ store_set_error_sqlite(store, "compare node prepare");
+ return CBM_STORE_ERR;
+ }
+ bind_text(cursor->stmt, SKIP_ONE, project);
+ return graph_node_cursor_step(store, cursor);
+}
+
+static int graph_prepare_edge_cursor(cbm_store_t *store, const char *project,
+ graph_edge_cursor_t *cursor) {
+ static const char sql[] =
+ "SELECT sn.qualified_name,sn.label,coalesce(sn.file_path,''),"
+ "tn.qualified_name,tn.label,coalesce(tn.file_path,''),e.type,"
+ "coalesce(e.local_name_gen,'') FROM edges e "
+ "JOIN nodes sn ON sn.id=e.source_id JOIN nodes tn ON tn.id=e.target_id "
+ "WHERE e.project=?1 ORDER BY "
+ "sn.qualified_name COLLATE BINARY,sn.label COLLATE BINARY,"
+ "coalesce(sn.file_path,'') COLLATE BINARY,"
+ "tn.qualified_name COLLATE BINARY,tn.label COLLATE BINARY,"
+ "coalesce(tn.file_path,'') COLLATE BINARY,"
+ "e.type COLLATE BINARY,coalesce(e.local_name_gen,'') COLLATE BINARY;";
+ if (sqlite3_prepare_v2(store->db, sql, CBM_NOT_FOUND, &cursor->stmt, NULL) != SQLITE_OK) {
+ store_set_error_sqlite(store, "compare edge prepare");
+ return CBM_STORE_ERR;
+ }
+ bind_text(cursor->stmt, SKIP_ONE, project);
+ return graph_edge_cursor_step(store, cursor);
+}
+
+static int graph_compare_nodes(cbm_store_t *base_store, const char *base_project,
+ cbm_store_t *target_store, const char *target_project,
+ graph_compare_progress_t *progress,
+ cbm_graph_compare_node_fn callback,
+ cbm_graph_compare_result_t *out) {
+ graph_node_cursor_t base = {0};
+ graph_node_cursor_t target = {0};
+ int rc = graph_prepare_node_cursor(base_store, base_project, &base);
+ if (rc == CBM_STORE_OK) {
+ rc = graph_prepare_node_cursor(target_store, target_project, &target);
+ }
+ uint64_t merged = 0;
+ while (rc == CBM_STORE_OK && (base.has_row || target.has_row)) {
+ if ((merged++ & UINT64_C(255)) == 0 && graph_compare_is_cancelled(progress)) {
+ rc = CBM_STORE_CANCELLED;
+ break;
+ }
+ int cmp =
+ !base.has_row
+ ? 1
+ : (!target.has_row ? -1 : graph_node_compare(&base.identity, &target.identity));
+ if (cmp < 0) {
+ out->nodes_removed_total++;
+ if (callback && !callback(progress->context, false, &base.identity)) {
+ rc = CBM_STORE_CALLBACK_ERR;
+ break;
+ }
+ rc = graph_node_cursor_step(base_store, &base);
+ } else if (cmp > 0) {
+ out->nodes_added_total++;
+ if (callback && !callback(progress->context, true, &target.identity)) {
+ rc = CBM_STORE_CALLBACK_ERR;
+ break;
+ }
+ rc = graph_node_cursor_step(target_store, &target);
+ } else {
+ rc = graph_node_cursor_step(base_store, &base);
+ if (rc == CBM_STORE_OK) {
+ rc = graph_node_cursor_step(target_store, &target);
+ }
+ }
+ }
+ sqlite3_finalize(base.stmt);
+ sqlite3_finalize(target.stmt);
+ return rc;
+}
+
+static int graph_compare_edges(cbm_store_t *base_store, const char *base_project,
+ cbm_store_t *target_store, const char *target_project,
+ graph_compare_progress_t *progress,
+ cbm_graph_compare_edge_fn callback,
+ cbm_graph_compare_result_t *out) {
+ graph_edge_cursor_t base = {0};
+ graph_edge_cursor_t target = {0};
+ int rc = graph_prepare_edge_cursor(base_store, base_project, &base);
+ if (rc == CBM_STORE_OK) {
+ rc = graph_prepare_edge_cursor(target_store, target_project, &target);
+ }
+ uint64_t merged = 0;
+ while (rc == CBM_STORE_OK && (base.has_row || target.has_row)) {
+ if ((merged++ & UINT64_C(255)) == 0 && graph_compare_is_cancelled(progress)) {
+ rc = CBM_STORE_CANCELLED;
+ break;
+ }
+ int cmp =
+ !base.has_row
+ ? 1
+ : (!target.has_row ? -1 : graph_edge_compare(&base.identity, &target.identity));
+ if (cmp < 0) {
+ out->edges_removed_total++;
+ if (callback && !callback(progress->context, false, &base.identity)) {
+ rc = CBM_STORE_CALLBACK_ERR;
+ break;
+ }
+ rc = graph_edge_cursor_step(base_store, &base);
+ } else if (cmp > 0) {
+ out->edges_added_total++;
+ if (callback && !callback(progress->context, true, &target.identity)) {
+ rc = CBM_STORE_CALLBACK_ERR;
+ break;
+ }
+ rc = graph_edge_cursor_step(target_store, &target);
+ } else {
+ rc = graph_edge_cursor_step(base_store, &base);
+ if (rc == CBM_STORE_OK) {
+ rc = graph_edge_cursor_step(target_store, &target);
+ }
+ }
+ }
+ sqlite3_finalize(base.stmt);
+ sqlite3_finalize(target.stmt);
+ return rc;
+}
+
+static bool graph_scan_limit_exceeded(int64_t base_count, int64_t target_count,
+ uint64_t scan_limit) {
+ if (base_count < 0 || target_count < 0 || (uint64_t)base_count > scan_limit ||
+ (uint64_t)target_count > scan_limit) {
+ return true;
+ }
+ return (uint64_t)base_count > scan_limit - (uint64_t)target_count;
+}
+
+int cbm_store_compare_graphs(cbm_store_t *base_store, const char *base_project,
+ cbm_store_t *target_store, const char *target_project,
+ uint64_t scan_limit, cbm_graph_compare_cancel_fn cancel,
+ cbm_graph_compare_node_fn on_node, cbm_graph_compare_edge_fn on_edge,
+ void *context, cbm_graph_compare_result_t *out) {
+ if (!base_store || !target_store || base_store == target_store || !base_project ||
+ !base_project[0] || !target_project || !target_project[0] || scan_limit == 0 || !out) {
+ return CBM_STORE_ERR;
+ }
+ memset(out, 0, sizeof(*out));
+ graph_compare_progress_t progress = {.cancel = cancel, .context = context};
+ if (graph_compare_is_cancelled(&progress)) {
+ return CBM_STORE_CANCELLED;
+ }
+
+ int rc = CBM_STORE_OK;
+ bool base_transaction = false;
+ bool target_transaction = false;
+ sqlite3_progress_handler(base_store->db, 1000, graph_compare_progress, &progress);
+ sqlite3_progress_handler(target_store->db, 1000, graph_compare_progress, &progress);
+
+ rc = exec_sql(base_store, "BEGIN;");
+ if (rc == CBM_STORE_OK) {
+ base_transaction = true;
+ rc = exec_sql(target_store, "BEGIN;");
+ }
+ if (rc == CBM_STORE_OK) {
+ target_transaction = true;
+ rc = graph_capture_project(base_store, base_project, &out->base);
+ }
+ if (rc == CBM_STORE_OK) {
+ rc = graph_capture_project(target_store, target_project, &out->target);
+ }
+ if (rc == CBM_STORE_OK &&
+ (graph_scan_limit_exceeded(out->base.node_count, out->target.node_count, scan_limit) ||
+ graph_scan_limit_exceeded(out->base.edge_count, out->target.edge_count, scan_limit))) {
+ rc = CBM_STORE_SCAN_LIMIT;
+ }
+ if (rc == CBM_STORE_OK) {
+ rc = graph_compare_nodes(base_store, base_project, target_store, target_project, &progress,
+ on_node, out);
+ }
+ if (rc == CBM_STORE_OK) {
+ rc = graph_compare_edges(base_store, base_project, target_store, target_project, &progress,
+ on_edge, out);
+ }
+ if (rc == CBM_STORE_OK && graph_compare_is_cancelled(&progress)) {
+ rc = CBM_STORE_CANCELLED;
+ }
+ if (rc != CBM_STORE_OK && graph_compare_is_cancelled(&progress)) {
+ rc = CBM_STORE_CANCELLED;
+ }
+
+ sqlite3_progress_handler(base_store->db, 0, NULL, NULL);
+ sqlite3_progress_handler(target_store->db, 0, NULL, NULL);
+ if (target_transaction && exec_sql(target_store, "ROLLBACK;") != CBM_STORE_OK &&
+ rc == CBM_STORE_OK) {
+ rc = CBM_STORE_ERR;
+ }
+ if (base_transaction && exec_sql(base_store, "ROLLBACK;") != CBM_STORE_OK &&
+ rc == CBM_STORE_OK) {
+ rc = CBM_STORE_ERR;
+ }
+ if (rc != CBM_STORE_OK) {
+ memset(out, 0, sizeof(*out));
+ }
+ return rc;
+}
+
/* ── Bulk write ─────────────────────────────────────────────────── */
int cbm_store_begin_bulk(cbm_store_t *s) {
diff --git a/src/store/store.h b/src/store/store.h
index 45a7bb439..43c189792 100644
--- a/src/store/store.h
+++ b/src/store/store.h
@@ -24,6 +24,9 @@ typedef struct cbm_store cbm_store_t;
#define CBM_STORE_ERR (-1)
#define CBM_STORE_NOT_FOUND (-2)
#define CBM_INDEX_FORMAT_VERSION 1
+#define CBM_STORE_CANCELLED (-3)
+#define CBM_STORE_SCAN_LIMIT (-4)
+#define CBM_STORE_CALLBACK_ERR (-5)
/* ── Data structures ────────────────────────────────────────────── */
@@ -255,6 +258,56 @@ typedef struct {
int sample_qn_count;
} cbm_schema_info_t;
+/* ── Graph comparison ──────────────────────────────────────────── */
+
+/* Stable graph identities deliberately exclude the project name. Strings are
+ * borrowed from the active SQLite row and remain valid only for the duration
+ * of the callback. */
+typedef struct {
+ const char *qualified_name;
+ const char *label;
+ const char *file_path;
+} cbm_graph_node_identity_t;
+
+typedef struct {
+ cbm_graph_node_identity_t source;
+ cbm_graph_node_identity_t target;
+ const char *type;
+ const char *local_name_gen;
+} cbm_graph_edge_identity_t;
+
+typedef bool (*cbm_graph_compare_cancel_fn)(void *context);
+typedef bool (*cbm_graph_compare_node_fn)(void *context, bool added,
+ const cbm_graph_node_identity_t *node);
+typedef bool (*cbm_graph_compare_edge_fn)(void *context, bool added,
+ const cbm_graph_edge_identity_t *edge);
+
+typedef struct {
+ char generation[128];
+ char index_mode[32];
+ int64_t node_count;
+ int64_t edge_count;
+} cbm_graph_compare_project_t;
+
+typedef struct {
+ cbm_graph_compare_project_t base;
+ cbm_graph_compare_project_t target;
+ uint64_t nodes_added_total;
+ uint64_t nodes_removed_total;
+ uint64_t edges_added_total;
+ uint64_t edges_removed_total;
+} cbm_graph_compare_result_t;
+
+/* Compare two independently-owned read-only stores using ordered streaming
+ * cursors. Both read transactions and both SQLite progress handlers are owned
+ * by this call and released on every exit. scan_limit applies independently to
+ * the combined node rows and combined edge rows across the two projects. */
+int cbm_store_compare_graphs(cbm_store_t *base_store, const char *base_project,
+ cbm_store_t *target_store, const char *target_project,
+ uint64_t scan_limit, cbm_graph_compare_cancel_fn cancel,
+ cbm_graph_compare_node_fn on_node, cbm_graph_compare_edge_fn on_edge,
+ void *context, cbm_graph_compare_result_t *out);
+
/* ── Lifecycle ──────────────────────────────────────────────────── */
/* Open an in-memory database (for testing). */
diff --git a/tests/test_mcp.c b/tests/test_mcp.c
index 6b7af64ed..fbf59823e 100644
--- a/tests/test_mcp.c
+++ b/tests/test_mcp.c
@@ -914,6 +914,7 @@ TEST(mcp_tools_have_behavior_annotations) {
{"trace_path", false, true, true, false},
{"get_code_snippet", false, true, true, false},
{"get_graph_schema", false, true, true, false},
+ {"compare_graphs", true, false, true, false},
{"get_architecture", false, true, true, false},
{"search_code", false, true, true, false},
{"list_projects", true, false, true, false},
@@ -1359,9 +1360,9 @@ TEST(server_handle_analysis_profile_filters_and_rejects_mutators) {
resp = cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":220,\"method\":\"tools/list\"}");
ASSERT_NOT_NULL(resp);
static const char *const analysis_tools[] = {
- "search_graph", "query_graph", "trace_path", "get_code_snippet",
- "get_graph_schema", "get_architecture", "search_code", "list_projects",
- "index_status", "check_index_coverage", "detect_changes",
+ "search_graph", "query_graph", "trace_path", "get_code_snippet",
+ "get_graph_schema", "compare_graphs", "get_architecture", "search_code",
+ "list_projects", "index_status", "check_index_coverage", "detect_changes",
};
ASSERT_EQ(mcp_response_tool_count(resp), sizeof(analysis_tools) / sizeof(analysis_tools[0]));
for (size_t i = 0U; i < sizeof(analysis_tools) / sizeof(analysis_tools[0]); i++) {
@@ -1411,6 +1412,7 @@ TEST(server_handle_scout_profile_exposes_only_the_fast_tier) {
ASSERT_FALSE(mcp_response_has_exact_tool(resp, "query_graph"));
ASSERT_FALSE(mcp_response_has_exact_tool(resp, "search_code"));
ASSERT_FALSE(mcp_response_has_exact_tool(resp, "get_graph_schema"));
+ ASSERT_FALSE(mcp_response_has_exact_tool(resp, "compare_graphs"));
ASSERT_FALSE(mcp_response_has_exact_tool(resp, "detect_changes"));
ASSERT_FALSE(mcp_response_has_exact_tool(resp, "index_repository"));
free(resp);
@@ -1670,6 +1672,24 @@ TEST(tool_unknown_tool) {
PASS();
}
+/* Issue #525: compare_graphs is a first-class analysis tool. The frozen base
+ * routes this call to the unknown-tool fallback; production registration is
+ * therefore required before any compare semantics can accidentally look green. */
+TEST(tool_compare_graphs_registered_issue525) {
+ cbm_mcp_server_t *srv = setup_mcp_with_data();
+
+ char *resp = cbm_mcp_server_handle(
+ srv, "{\"jsonrpc\":\"2.0\",\"id\":525,\"method\":\"tools/call\","
+ "\"params\":{\"name\":\"compare_graphs\",\"arguments\":{"
+ "\"base_project\":\"base525\",\"target_project\":\"target525\"}}}");
+ ASSERT_NOT_NULL(resp);
+ ASSERT_NULL(strstr(resp, "unknown tool: compare_graphs"));
+ free(resp);
+
+ cbm_mcp_server_free(srv);
+ PASS();
+}
+
TEST(tool_search_graph_basic) {
cbm_mcp_server_t *srv = setup_mcp_with_data();
@@ -7923,6 +7943,485 @@ static char *extract_text_content(const char *mcp_result) {
return result;
}
+typedef struct {
+ char cache[512];
+ char base_path[768];
+ char target_path[768];
+ char *saved_cache;
+} compare_graphs_fixture_t;
+
+typedef struct {
+ const char *qualified_name;
+ const char *label;
+ const char *file_path;
+} compare_node_spec_t;
+
+static bool compare_write_coverage(cbm_store_t *store, const char *project,
+ const char *generation) {
+ cbm_coverage_meta_t meta = {
+ .generation = generation,
+ .index_mode = "full",
+ .recorded_at = "2026-08-28T00:00:00Z",
+ .recording_status = "complete",
+ .ignored_files_stored = 0,
+ .ignored_files_total = 0,
+ .coverage_version = 1,
+ .hash_records_complete = true,
+ };
+ return cbm_store_coverage_replace_ex(store, project, NULL, 0, &meta) == CBM_STORE_OK;
+}
+
+static bool compare_write_fixture_store(const char *path, const char *project, bool target) {
+ static const compare_node_spec_t base_nodes[] = {
+ {"pkg.common", "Function", "src/common.c"}, {"pkg.base", "Function", "src/base.c"},
+ {"pkg.changed", "Function", "src/old.c"}, {"pkg.source", "Module", "src/source.c"},
+ {"pkg.sink", "Module", "src/sink.c"},
+ };
+ static const compare_node_spec_t target_nodes[] = {
+ {"pkg.common", "Function", "src/common.c"}, {"pkg.target", "Function", "src/target.c"},
+ {"pkg.changed", "Method", "src/new.c"}, {"pkg.source", "Module", "src/source.c"},
+ {"pkg.sink", "Module", "src/sink.c"},
+ };
+ static const int base_order[] = {3, 2, 0, 4, 1};
+ static const int target_order[] = {1, 4, 0, 2, 3};
+ const compare_node_spec_t *nodes = target ? target_nodes : base_nodes;
+ const int *order = target ? target_order : base_order;
+
+ cbm_store_t *store = cbm_store_open_path(path);
+ if (!store ||
+ cbm_store_upsert_project(store, project, "/tmp/compare-graphs-525") != CBM_STORE_OK) {
+ cbm_store_close(store);
+ return false;
+ }
+ int64_t ids[5] = {0};
+ bool ok = true;
+ for (size_t position = 0; position < 5; position++) {
+ int index = order[position];
+ cbm_node_t node = {
+ .project = project,
+ .label = nodes[index].label,
+ .name = nodes[index].qualified_name,
+ .qualified_name = nodes[index].qualified_name,
+ .file_path = nodes[index].file_path,
+ .properties_json = "{}",
+ };
+ ids[index] = cbm_store_upsert_node(store, &node);
+ ok = ok && ids[index] > 0;
+ }
+
+ cbm_edge_t common_call = {
+ .project = project,
+ .source_id = ids[3],
+ .target_id = ids[4],
+ .type = "CALLS",
+ .properties_json = "{}",
+ };
+ cbm_edge_t common_import = {
+ .project = project,
+ .source_id = ids[3],
+ .target_id = ids[4],
+ .type = "IMPORTS",
+ .properties_json = "{\"local_name\":\"Alpha\"}",
+ };
+ cbm_edge_t changed_import = {
+ .project = project,
+ .source_id = ids[3],
+ .target_id = ids[4],
+ .type = "IMPORTS",
+ .properties_json = target ? "{\"local_name\":\"Gamma\"}" : "{\"local_name\":\"Beta\"}",
+ };
+ cbm_edge_t side_edge = {
+ .project = project,
+ .source_id = ids[1],
+ .target_id = ids[0],
+ .type = "USES",
+ .properties_json = "{}",
+ };
+ if (target) {
+ ok = ok && cbm_store_insert_edge(store, &side_edge) > 0 &&
+ cbm_store_insert_edge(store, &changed_import) > 0 &&
+ cbm_store_insert_edge(store, &common_call) > 0 &&
+ cbm_store_insert_edge(store, &common_import) > 0;
+ } else {
+ ok = ok && cbm_store_insert_edge(store, &common_import) > 0 &&
+ cbm_store_insert_edge(store, &common_call) > 0 &&
+ cbm_store_insert_edge(store, &side_edge) > 0 &&
+ cbm_store_insert_edge(store, &changed_import) > 0;
+ }
+ ok = ok &&
+ compare_write_coverage(store, project,
+ target ? "target-generation-525" : "base-generation-525") &&
+ cbm_store_prepare_for_publish(store) == CBM_STORE_OK;
+ cbm_store_close(store);
+ return ok;
+}
+
+static bool compare_graphs_fixture_open(compare_graphs_fixture_t *fixture) {
+ memset(fixture, 0, sizeof(*fixture));
+ snprintf(fixture->cache, sizeof(fixture->cache), "%s/cbm-compare-525-XXXXXX", cbm_tmpdir());
+ if (!cbm_mkdtemp(fixture->cache)) {
+ return false;
+ }
+ const char *saved = getenv("CBM_CACHE_DIR");
+ fixture->saved_cache = saved ? strdup(saved) : NULL;
+ if ((saved && !fixture->saved_cache) || cbm_setenv("CBM_CACHE_DIR", fixture->cache, 1) != 0) {
+ free(fixture->saved_cache);
+ fixture->saved_cache = NULL;
+ (void)th_rmtree(fixture->cache);
+ return false;
+ }
+ snprintf(fixture->base_path, sizeof(fixture->base_path), "%s/base525.db", fixture->cache);
+ snprintf(fixture->target_path, sizeof(fixture->target_path), "%s/target525.db", fixture->cache);
+ if (!compare_write_fixture_store(fixture->base_path, "base525", false) ||
+ !compare_write_fixture_store(fixture->target_path, "target525", true)) {
+ restore_cache_dir(fixture->saved_cache);
+ free(fixture->saved_cache);
+ fixture->saved_cache = NULL;
+ (void)th_rmtree(fixture->cache);
+ return false;
+ }
+ return true;
+}
+
+static bool compare_graphs_fixture_close(compare_graphs_fixture_t *fixture) {
+ restore_cache_dir(fixture->saved_cache);
+ free(fixture->saved_cache);
+ fixture->saved_cache = NULL;
+ return th_rmtree(fixture->cache) == 0;
+}
+
+static char *compare_graphs_call(cbm_mcp_server_t *server, const char *extra_arguments) {
+ char arguments[1024];
+ snprintf(arguments, sizeof(arguments),
+ "{\"base_project\":\"base525\",\"target_project\":\"target525\"%s}",
+ extra_arguments ? extra_arguments : "");
+ return cbm_mcp_handle_tool(server, "compare_graphs", arguments);
+}
+
+static bool compare_set_has(const yyjson_val *set, uint64_t total, uint64_t returned,
+ bool truncated, const char *reason) {
+ if (!set || !yyjson_is_obj(set)) {
+ return false;
+ }
+ yyjson_val *items = yyjson_obj_get(set, "items");
+ yyjson_val *reasons = yyjson_obj_get(set, "truncation_reasons");
+ return items && yyjson_is_arr(items) && yyjson_arr_size(items) == returned && reasons &&
+ yyjson_is_arr(reasons) && yyjson_get_uint(yyjson_obj_get(set, "total")) == total &&
+ yyjson_get_uint(yyjson_obj_get(set, "returned")) == returned &&
+ yyjson_get_bool(yyjson_obj_get(set, "truncated")) == truncated &&
+ ((!reason && yyjson_arr_size(reasons) == 0) ||
+ (reason && yyjson_arr_size(reasons) == 1 &&
+ strcmp(yyjson_get_str(yyjson_arr_get(reasons, 0)), reason) == 0));
+}
+
+TEST(tool_compare_graphs_streams_stable_deltas_issue525) {
+ compare_graphs_fixture_t fixture;
+ ASSERT_TRUE(compare_graphs_fixture_open(&fixture));
+ cbm_mcp_server_t *server = cbm_mcp_server_new(NULL);
+ ASSERT_NOT_NULL(server);
+ cbm_mcp_server_set_tool_profile(server, CBM_MCP_TOOL_PROFILE_ANALYSIS);
+
+ char *first = compare_graphs_call(server, NULL);
+ char *second = compare_graphs_call(server, NULL);
+ ASSERT_NOT_NULL(first);
+ ASSERT_NOT_NULL(second);
+ ASSERT_STR_EQ(first, second);
+ ASSERT_NOT_NULL(strstr(first, "\"isError\":false"));
+ char *inner = extract_text_content(first);
+ 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, "schema_version")), 1);
+
+ yyjson_val *base = yyjson_obj_get(root, "base");
+ yyjson_val *target = yyjson_obj_get(root, "target");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(base, "project")), "base525");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(base, "generation")), "base-generation-525");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(base, "index_mode")), "full");
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(base, "node_count")), 5);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(base, "edge_count")), 4);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(target, "project")), "target525");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(target, "generation")), "target-generation-525");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(target, "index_mode")), "full");
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(target, "node_count")), 5);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(target, "edge_count")), 4);
+
+ yyjson_val *nodes = yyjson_obj_get(root, "nodes");
+ yyjson_val *nodes_added = yyjson_obj_get(nodes, "added");
+ yyjson_val *nodes_removed = yyjson_obj_get(nodes, "removed");
+ ASSERT_TRUE(compare_set_has(nodes_added, 2, 2, false, NULL));
+ ASSERT_TRUE(compare_set_has(nodes_removed, 2, 2, false, NULL));
+ yyjson_val *added_items = yyjson_obj_get(nodes_added, "items");
+ yyjson_val *removed_items = yyjson_obj_get(nodes_removed, "items");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(added_items, 0), "qualified_name")),
+ "pkg.changed");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(added_items, 0), "label")),
+ "Method");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(added_items, 0), "file_path")),
+ "src/new.c");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(added_items, 1), "qualified_name")),
+ "pkg.target");
+ ASSERT_STR_EQ(
+ yyjson_get_str(yyjson_obj_get(yyjson_arr_get(removed_items, 0), "qualified_name")),
+ "pkg.base");
+ ASSERT_STR_EQ(
+ yyjson_get_str(yyjson_obj_get(yyjson_arr_get(removed_items, 1), "qualified_name")),
+ "pkg.changed");
+
+ yyjson_val *edges = yyjson_obj_get(root, "edges");
+ yyjson_val *edges_added = yyjson_obj_get(edges, "added");
+ yyjson_val *edges_removed = yyjson_obj_get(edges, "removed");
+ ASSERT_TRUE(compare_set_has(edges_added, 2, 2, false, NULL));
+ ASSERT_TRUE(compare_set_has(edges_removed, 2, 2, false, NULL));
+ yyjson_val *edge_add_items = yyjson_obj_get(edges_added, "items");
+ yyjson_val *edge_remove_items = yyjson_obj_get(edges_removed, "items");
+ ASSERT_STR_EQ(
+ yyjson_get_str(yyjson_obj_get(yyjson_arr_get(edge_add_items, 0), "local_name_gen")),
+ "Gamma");
+ ASSERT_STR_EQ(
+ yyjson_get_str(yyjson_obj_get(yyjson_arr_get(edge_remove_items, 1), "local_name_gen")),
+ "Beta");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(edge_add_items, 1), "type")),
+ "USES");
+ ASSERT_STR_EQ(
+ yyjson_get_str(yyjson_obj_get(yyjson_arr_get(edge_add_items, 1), "local_name_gen")), "");
+ yyjson_val *edge_source = yyjson_obj_get(yyjson_arr_get(edge_add_items, 0), "source");
+ yyjson_val *edge_target = yyjson_obj_get(yyjson_arr_get(edge_add_items, 0), "target");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(edge_source, "qualified_name")), "pkg.source");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(edge_target, "qualified_name")), "pkg.sink");
+
+ yyjson_val *limits = yyjson_obj_get(root, "limits");
+ ASSERT_EQ(yyjson_get_uint(yyjson_obj_get(limits, "limit")), 200);
+ ASSERT_EQ(yyjson_get_uint(yyjson_obj_get(limits, "scan_limit")), 2000000);
+ ASSERT_EQ(yyjson_get_uint(yyjson_obj_get(limits, "encoded_byte_budget")), 512U * 1024U);
+ yyjson_doc_free(doc);
+ free(inner);
+ free(second);
+ free(first);
+
+ char *limited = compare_graphs_call(server, ",\"limit\":1");
+ ASSERT_NOT_NULL(limited);
+ inner = extract_text_content(limited);
+ doc = yyjson_read(inner, strlen(inner), 0);
+ ASSERT_NOT_NULL(doc);
+ root = yyjson_doc_get_root(doc);
+ nodes = yyjson_obj_get(root, "nodes");
+ edges = yyjson_obj_get(root, "edges");
+ ASSERT_TRUE(compare_set_has(yyjson_obj_get(nodes, "added"), 2, 1, true, "limit"));
+ ASSERT_TRUE(compare_set_has(yyjson_obj_get(nodes, "removed"), 2, 1, true, "limit"));
+ ASSERT_TRUE(compare_set_has(yyjson_obj_get(edges, "added"), 2, 1, true, "limit"));
+ ASSERT_TRUE(compare_set_has(yyjson_obj_get(edges, "removed"), 2, 1, true, "limit"));
+ yyjson_doc_free(doc);
+ free(inner);
+ free(limited);
+
+ cbm_mcp_server_free(server);
+ ASSERT_TRUE(compare_graphs_fixture_close(&fixture));
+ PASS();
+}
+
+static bool compare_write_single_node_store(const char *path, const char *project,
+ const char *generation, const char *qualified_name) {
+ cbm_store_t *store = cbm_store_open_path(path);
+ if (!store ||
+ cbm_store_upsert_project(store, project, "/tmp/compare-budget-525") != CBM_STORE_OK) {
+ cbm_store_close(store);
+ return false;
+ }
+ bool ok = true;
+ if (qualified_name) {
+ cbm_node_t node = {
+ .project = project,
+ .label = "Function",
+ .name = "large",
+ .qualified_name = qualified_name,
+ .file_path = "src/large.c",
+ .properties_json = "{}",
+ };
+ ok = cbm_store_upsert_node(store, &node) > 0;
+ }
+ ok = ok && compare_write_coverage(store, project, generation) &&
+ cbm_store_prepare_for_publish(store) == CBM_STORE_OK;
+ cbm_store_close(store);
+ return ok;
+}
+
+TEST(tool_compare_graphs_enforces_encoded_budget_issue525) {
+ compare_graphs_fixture_t fixture;
+ ASSERT_TRUE(compare_graphs_fixture_open(&fixture));
+ char base_path[768];
+ char target_path[768];
+ snprintf(base_path, sizeof(base_path), "%s/budgetbase525.db", fixture.cache);
+ snprintf(target_path, sizeof(target_path), "%s/budgettarget525.db", fixture.cache);
+ size_t name_length = 530000U;
+ char *large_name = malloc(name_length + 1U);
+ ASSERT_NOT_NULL(large_name);
+ memset(large_name, 'x', name_length);
+ large_name[0] = 'z';
+ large_name[name_length] = '\0';
+ ASSERT_TRUE(compare_write_single_node_store(base_path, "budgetbase525", "budget-base", NULL));
+ ASSERT_TRUE(compare_write_single_node_store(target_path, "budgettarget525", "budget-target",
+ large_name));
+ free(large_name);
+
+ cbm_mcp_server_t *server = cbm_mcp_server_new(NULL);
+ ASSERT_NOT_NULL(server);
+ char *response = cbm_mcp_handle_tool(
+ server, "compare_graphs",
+ "{\"base_project\":\"budgetbase525\",\"target_project\":\"budgettarget525\","
+ "\"limit\":1000}");
+ ASSERT_NOT_NULL(response);
+ ASSERT_LT(strlen(response), 10000U);
+ char *inner = extract_text_content(response);
+ yyjson_doc *doc = inner ? yyjson_read(inner, strlen(inner), 0) : NULL;
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *nodes = yyjson_obj_get(yyjson_doc_get_root(doc), "nodes");
+ ASSERT_TRUE(compare_set_has(yyjson_obj_get(nodes, "added"), 1, 0, true, "encoded_byte_budget"));
+ yyjson_doc_free(doc);
+ free(inner);
+ free(response);
+ cbm_mcp_server_free(server);
+ ASSERT_TRUE(compare_graphs_fixture_close(&fixture));
+ PASS();
+}
+
+TEST(tool_compare_graphs_validation_and_scan_cap_are_atomic_issue525) {
+ compare_graphs_fixture_t fixture;
+ ASSERT_TRUE(compare_graphs_fixture_open(&fixture));
+ cbm_mcp_server_t *server = cbm_mcp_server_new(NULL);
+ ASSERT_NOT_NULL(server);
+
+ char equal_path[768];
+ char equal_wal[800];
+ char equal_shm[800];
+ snprintf(equal_path, sizeof(equal_path), "%s/same525.db", fixture.cache);
+ snprintf(equal_wal, sizeof(equal_wal), "%s-wal", equal_path);
+ snprintf(equal_shm, sizeof(equal_shm), "%s-shm", equal_path);
+ ASSERT_FALSE(cbm_file_exists(equal_path));
+
+ static const char *const invalid_arguments[] = {
+ "{}",
+ "{\"base_project\":\"same525\",\"target_project\":\"same525\"}",
+ "{\"base_project\":\"base525\",\"target_project\":\"target525\",\"limit\":0}",
+ "{\"base_project\":\"base525\",\"target_project\":\"target525\",\"limit\":1001}",
+ "{\"base_project\":\"base525\",\"target_project\":\"target525\",\"scan_limit\":0}",
+ ("{\"base_project\":\"base525\",\"target_project\":\"target525\","
+ "\"scan_limit\":10000001}"),
+ "{\"base_project\":\"base525\",\"target_project\":\"target525\",\"extra\":1}",
+ "{",
+ };
+ for (size_t index = 0; index < sizeof(invalid_arguments) / sizeof(invalid_arguments[0]);
+ index++) {
+ char *response = cbm_mcp_handle_tool(server, "compare_graphs", invalid_arguments[index]);
+ ASSERT_NOT_NULL(response);
+ ASSERT_NOT_NULL(strstr(response, "\"isError\":true"));
+ char *inner = extract_text_content(response);
+ ASSERT_NOT_NULL(inner);
+ ASSERT_NULL(strstr(inner, "\"nodes\""));
+ free(inner);
+ free(response);
+ }
+ ASSERT_FALSE(cbm_file_exists(equal_path));
+ ASSERT_FALSE(cbm_file_exists(equal_wal));
+ ASSERT_FALSE(cbm_file_exists(equal_shm));
+
+ char ghost_path[768];
+ char ghost_wal[800];
+ char ghost_shm[800];
+ snprintf(ghost_path, sizeof(ghost_path), "%s/ghost525.db", fixture.cache);
+ snprintf(ghost_wal, sizeof(ghost_wal), "%s-wal", ghost_path);
+ snprintf(ghost_shm, sizeof(ghost_shm), "%s-shm", ghost_path);
+ ASSERT_FALSE(cbm_file_exists(ghost_path));
+ char *missing = cbm_mcp_handle_tool(
+ server, "compare_graphs", "{\"base_project\":\"base525\",\"target_project\":\"ghost525\"}");
+ ASSERT_NOT_NULL(missing);
+ ASSERT_NOT_NULL(strstr(missing, "project_not_indexed"));
+ ASSERT_FALSE(cbm_file_exists(ghost_path));
+ ASSERT_FALSE(cbm_file_exists(ghost_wal));
+ ASSERT_FALSE(cbm_file_exists(ghost_shm));
+ free(missing);
+
+ char *scan_limited = compare_graphs_call(server, ",\"scan_limit\":1");
+ ASSERT_NOT_NULL(scan_limited);
+ ASSERT_NOT_NULL(strstr(scan_limited, "scan_limit_exceeded"));
+ char *scan_inner = extract_text_content(scan_limited);
+ ASSERT_NOT_NULL(scan_inner);
+ ASSERT_NULL(strstr(scan_inner, "\"nodes\""));
+ free(scan_inner);
+ free(scan_limited);
+
+ char *malformed_rpc = cbm_mcp_server_handle(server, "{");
+ ASSERT_NOT_NULL(malformed_rpc);
+ ASSERT_NOT_NULL(strstr(malformed_rpc, "-32700"));
+ free(malformed_rpc);
+ cbm_mcp_server_free(server);
+ ASSERT_TRUE(compare_graphs_fixture_close(&fixture));
+ PASS();
+}
+
+TEST(tool_compare_graphs_cancel_and_readonly_handles_release_issue525) {
+ compare_graphs_fixture_t fixture;
+ ASSERT_TRUE(compare_graphs_fixture_open(&fixture));
+ long base_length = 0;
+ long target_length = 0;
+ unsigned char *base_before = mcp_read_file_bytes(fixture.base_path, &base_length);
+ unsigned char *target_before = mcp_read_file_bytes(fixture.target_path, &target_length);
+ ASSERT_NOT_NULL(base_before);
+ ASSERT_NOT_NULL(target_before);
+ char base_wal[800];
+ char base_shm[800];
+ char target_wal[800];
+ char target_shm[800];
+ snprintf(base_wal, sizeof(base_wal), "%s-wal", fixture.base_path);
+ snprintf(base_shm, sizeof(base_shm), "%s-shm", fixture.base_path);
+ snprintf(target_wal, sizeof(target_wal), "%s-wal", fixture.target_path);
+ snprintf(target_shm, sizeof(target_shm), "%s-shm", fixture.target_path);
+ ASSERT_FALSE(cbm_file_exists(base_wal));
+ ASSERT_FALSE(cbm_file_exists(base_shm));
+ ASSERT_FALSE(cbm_file_exists(target_wal));
+ ASSERT_FALSE(cbm_file_exists(target_shm));
+
+ cbm_mcp_server_t *server = cbm_mcp_server_new(NULL);
+ ASSERT_NOT_NULL(server);
+ ASSERT_TRUE(cbm_mcp_server_request_scope_begin(server));
+ ASSERT_TRUE(cbm_mcp_server_cancel_active(server));
+ char *cancelled = compare_graphs_call(server, NULL);
+ ASSERT_NOT_NULL(cancelled);
+ ASSERT_NOT_NULL(strstr(cancelled, "\"isError\":true"));
+ ASSERT_NOT_NULL(strstr(cancelled, "cancelled"));
+ char *cancelled_inner = extract_text_content(cancelled);
+ ASSERT_NOT_NULL(cancelled_inner);
+ ASSERT_NULL(strstr(cancelled_inner, "\"nodes\""));
+ free(cancelled_inner);
+ free(cancelled);
+ cbm_mcp_server_request_scope_end(server);
+
+ char moved_path[800];
+ snprintf(moved_path, sizeof(moved_path), "%s/base525.moved", fixture.cache);
+ ASSERT_EQ(rename(fixture.base_path, moved_path), 0);
+ ASSERT_EQ(rename(moved_path, fixture.base_path), 0);
+
+ char *success = compare_graphs_call(server, NULL);
+ ASSERT_NOT_NULL(success);
+ ASSERT_NOT_NULL(strstr(success, "\"isError\":false"));
+ free(success);
+ ASSERT_EQ(rename(fixture.base_path, moved_path), 0);
+ ASSERT_EQ(rename(moved_path, fixture.base_path), 0);
+ ASSERT_TRUE(mcp_file_matches_snapshot(fixture.base_path, base_before, base_length));
+ ASSERT_TRUE(mcp_file_matches_snapshot(fixture.target_path, target_before, target_length));
+ ASSERT_FALSE(cbm_file_exists(base_wal));
+ ASSERT_FALSE(cbm_file_exists(base_shm));
+ ASSERT_FALSE(cbm_file_exists(target_wal));
+ ASSERT_FALSE(cbm_file_exists(target_shm));
+
+ free(base_before);
+ free(target_before);
+ cbm_mcp_server_free(server);
+ ASSERT_TRUE(compare_graphs_fixture_close(&fixture));
+ PASS();
+}
+
/* Call get_code_snippet and extract inner text content.
* Caller must free returned string. */
static char *call_snippet(cbm_mcp_server_t *srv, const char *args_json) {
@@ -11551,6 +12050,11 @@ SUITE(mcp) {
RUN_TEST(tool_list_projects_empty);
RUN_TEST(tool_get_graph_schema_empty);
RUN_TEST(tool_unknown_tool);
+ RUN_TEST(tool_compare_graphs_registered_issue525);
+ RUN_TEST(tool_compare_graphs_streams_stable_deltas_issue525);
+ RUN_TEST(tool_compare_graphs_enforces_encoded_budget_issue525);
+ RUN_TEST(tool_compare_graphs_validation_and_scan_cap_are_atomic_issue525);
+ RUN_TEST(tool_compare_graphs_cancel_and_readonly_handles_release_issue525);
RUN_TEST(tool_search_graph_basic);
RUN_TEST(tool_search_graph_semantic_only_skips_structural_results_issue1295);
RUN_TEST(tool_trace_totals_respect_test_filter);