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 remote-tracking branch 'origin/main' into feat/shared-coordination-daemon
Martin Vogel5d8a9421fb85
diff --cc src/mcp/mcp.cindex 47aed5b83,a04057419..8709bb74a--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@@ -1399,20 -1416,8 +1444,22 @@@ struct cbm_mcp_serverchar session_root[CBM_SZ_1K]; /* detected project root path */char session_project[CBM_SZ_256]; /* derived project name */bool session_detected; /* true after first detection attempt */+ char *allowed_root; /* explicit per-session boundary (heap, nullable) */+ bool allowed_root_policy_set; /* true even when explicit policy is unrestricted */+ bool background_tasks; /* per-server update/auto-index work enabled */struct cbm_watcher *watcher; /* external watcher ref (not owned) */struct cbm_config *config; /* external config ref (not owned) */+ cbm_mcp_index_executor_fn index_executor;+ void *index_executor_context;+ cbm_proc_log_cb index_log_callback;+ void *index_log_context;+ cbm_mcp_project_mutation_begin_fn mutation_begin;+ cbm_mcp_project_mutation_end_fn mutation_end;+ void *mutation_context;+ cbm_mcp_quarantine_test_hook_fn quarantine_test_hook;+ void *quarantine_test_context;++ cbm_mcp_command_test_hook_fn command_test_hook;++ void *command_test_context;cbm_thread_t autoindex_tid;bool autoindex_active; /* true if auto-index thread was started */@@@ -1636,62 -1530,6 +1683,71 @@@ cbm_pipeline_t *cbm_mcp_server_active_preturn srv ? srv->active_pipeline : NULL;}+bool cbm_mcp_server_cancel_active(cbm_mcp_server_t *srv) {+ if (!srv) {+ return false;+ }+ cbm_mutex_lock(&srv->request_scope_mutex);+ bool active = srv->request_scope_depth != 0;+ if (active) {+ atomic_store_explicit(&srv->pipeline_cancel_requested, 1, memory_order_release);+ }+ cbm_mutex_unlock(&srv->request_scope_mutex);+ return active;+}++bool cbm_mcp_server_request_scope_begin(cbm_mcp_server_t *srv) {+ if (!srv) {+ return false;+ }+ cbm_mutex_lock(&srv->request_scope_mutex);+ bool available = srv->request_scope_depth < UINT_MAX;+ if (available) {+ if (srv->request_scope_depth == 0) {+ atomic_store_explicit(&srv->pipeline_cancel_requested, 0, memory_order_release);+ }+ srv->request_scope_depth++;+ }+ cbm_mutex_unlock(&srv->request_scope_mutex);+ return available;+}++void cbm_mcp_server_request_scope_end(cbm_mcp_server_t *srv) {+ if (!srv) {+ return;+ }+ cbm_mutex_lock(&srv->request_scope_mutex);+ if (srv->request_scope_depth > 0) {+ srv->request_scope_depth--;+ if (srv->request_scope_depth == 0) {+ atomic_store_explicit(&srv->pipeline_cancel_requested, 0, memory_order_release);+ }+ }+ cbm_mutex_unlock(&srv->request_scope_mutex);+}++static bool mcp_request_cancelled(const cbm_mcp_server_t *srv) {+ return srv && atomic_load_explicit(&srv->pipeline_cancel_requested, memory_order_acquire) != 0;+}++void cbm_mcp_server_set_quarantine_test_hook(cbm_mcp_server_t *srv,+ cbm_mcp_quarantine_test_hook_fn hook, void *context) {+ if (!srv) {+ return;+ }+ srv->quarantine_test_hook = hook;+ srv->quarantine_test_context = context;+}+++void cbm_mcp_server_set_command_test_hook(cbm_mcp_server_t *srv, cbm_mcp_command_test_hook_fn hook,++ void *context) {++ if (!srv) {++ return;++ }++ srv->command_test_hook = hook;++ srv->command_test_context = context;++}++/* ── Cache dir + project DB path helpers ───────────────────────── *//* Returns the cache directory. Writes to buf, returns buf for convenience. */@@@ -8238,93 -8549,11 +9385,100 @@@ static char *handle_search_code(cbm_mcp/* ── detect_changes ───────────────────────────────────────────── */+/* Run shell-backed query helpers inside the same process-tree containment used+ * by indexing. A plain popen owns only its shell stream: on disconnect there is+ * no safe handle with which to stop a blocked git child or its descendants. */+static bool mcp_command_output_path(char out[CBM_SZ_2K]) {+ char directory[CBM_SZ_1K];+ const char *cache = cbm_resolve_cache_dir();+ int written;+ if (cache && cache[0]) {+ written = snprintf(directory, sizeof(directory), "%s/logs", cache);+ if (written <= 0 || written >= (int)sizeof(directory) || !cbm_mkdir_p(directory, 0700)) {+ return false;+ }+ } else {+ written = snprintf(directory, sizeof(directory), "%s", cbm_tmpdir());+ if (written <= 0 || written >= (int)sizeof(directory)) {+ return false;+ }+ }+ written = snprintf(out, CBM_SZ_2K, "%s/.mcp-command-XXXXXX", directory);+ if (written <= 0 || written >= CBM_SZ_2K) {+ out[0] = '\0';+ return false;+ }+ int descriptor = cbm_mkstemp(out);+ if (descriptor < 0) {+ out[0] = '\0';+ return false;+ }+#ifdef _WIN32+ (void)_close(descriptor);+#else+ (void)close(descriptor);+#endif+ return true;+}++static int mcp_run_shell_command_cancellable(cbm_mcp_server_t *srv, const char *command,+ char output_path[CBM_SZ_2K],+ cbm_proc_result_t *result_out) {+ if (!srv || !command || !output_path || !result_out || !mcp_command_output_path(output_path)) {+ return -1;+ }++ /* Internal test seam: rejecting after output allocation exercises the same++ * cleanup contract as a contained process-tree failure. */++ if (srv->command_test_hook && !srv->command_test_hook(srv->command_test_context, command)) {++ return -1;++ }+#ifdef _WIN32+ const char *shell = getenv("COMSPEC");+ if (!shell || !shell[0]) {+ shell = "cmd.exe";+ }+ const char *argv[] = {shell, "/D", "/S", "/C", command, NULL};+#else+ const char *shell = "/bin/sh";+ const char *argv[] = {"sh", "-c", command, NULL};+#endif+ cbm_proc_opts_t options = {+ .bin = shell,+ .argv = argv,+ .log_file = output_path,+ .quiet_timeout_ms = 0,+ .cancel_grace_ms = CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS,+ .delete_log_on_exit = false,+ };+ cbm_subprocess_t *process = NULL;+ if (cbm_subprocess_spawn(&options, &process) != 0) {+ (void)cbm_unlink(output_path);+ output_path[0] = '\0';+ return -1;+ }++ cbm_proc_poll_t state;+ for (;;) {+ if (mcp_request_cancelled(srv)) {+ (void)cbm_subprocess_request_cancel(process);+ }+ state = cbm_subprocess_poll(process, result_out);+ if (state != CBM_PROC_POLL_RUNNING) {+ break;+ }+ cbm_usleep(10000);+ }+ bool contained = state == CBM_PROC_POLL_TERMINAL && result_out->tree_quiesced &&+ !result_out->supervision_failed;+ cbm_subprocess_destroy(process);+ return contained ? 0 : -1;+}+- /* Find symbols defined in a file and add them to the impacted array. */- static void detect_add_impacted_symbols(cbm_store_t *store, const char *project, const char *file,- yyjson_mut_doc *doc, yyjson_mut_val *impacted) {+ /* Collect BFS seed ids: every symbol DEFINED in a changed file (everything but+ * the structural container labels — those have no CALLS edges). These anchor+ * the multi-source impact traversal. */+ static void detect_collect_seeds(cbm_store_t *store, const char *project, const char *file,+ int64_t **seeds, int *n, int *cap) {cbm_node_t *nodes = NULL;int ncount = 0;cbm_store_find_nodes_by_file(store, project, file, &nodes, &ncount);@@@ -8449,29 -8773,58 +9710,68 @@@ static char *handle_detect_changes(cbm_free(scope);return cbm_mcp_text_result(errmsg, true);}+ FILE *fp = cbm_fopen(output_path, "rb");+ if (!fp) {+ (void)cbm_unlink(output_path);+ free(root_path);+ free(project);+ free(base_branch);+ free(scope);+ return cbm_mcp_text_result("git diff failed: contained output could not be read", true);+ }- yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);- yyjson_mut_val *root_obj = yyjson_mut_obj(doc);- yyjson_mut_doc_set_root(doc, root_obj);-- yyjson_mut_val *changed = yyjson_mut_arr(doc);- yyjson_mut_val *impacted = yyjson_mut_arr(doc);-/* resolve_store already called via get_project_root above */cbm_store_t *store = srv->store;- char line[CBM_SZ_1K];+ /* Direction of impact. Default inbound = the BLAST RADIUS: the transitive+ * CALLERS of the changed symbols, which may need review. outbound = what+ * the changed code depends on; both = union. */+ char *direction = cbm_mcp_get_string_arg(args, "direction");+ if (!direction) {+ direction = heap_strdup("inbound");+ }+ /* Teaching error, same contract as trace_path: never silently correct an+ * unknown direction — the caller would misread the result's semantics. */+ if (strcmp(direction, "inbound") != 0 && strcmp(direction, "outbound") != 0 &&+ strcmp(direction, "both") != 0) {+ char errbuf[CBM_SZ_256];+ snprintf(errbuf, sizeof(errbuf),+ "invalid direction \"%s\" — use \"inbound\" (blast radius: transitive callers), "+ "\"outbound\" (dependencies), or \"both\"",+ direction);+ free(direction);+ free(root_path);+ free(project);+ free(base_branch);+ free(scope);- (void)cbm_pclose(fp);++ (void)fclose(fp);++ (void)cbm_unlink(output_path);+ return cbm_mcp_text_result(errbuf, true);+ }+ char *fmt = cbm_mcp_get_string_arg(args, "format");+ bool legacy_json = fmt && strcmp(fmt, "json") == 0;+ free(fmt);++ /* Per-symbol impacted-row display cap (the module rollup stays complete).+ * impacted_total always reports the true count, so this never hides scale. */+ int imp_limit = cbm_mcp_get_int_arg(args, "limit", MCP_DEFAULT_IMPACT_LIMIT);+ if (imp_limit < 1) {+ imp_limit = 1;+ }+ if (imp_limit > MCP_BFS_LIMIT_MAX) {+ imp_limit = MCP_BFS_LIMIT_MAX;+ }++ /* Collect changed file paths into a C array (drives seeds, the rollup, and+ * both output encodings). */+ char **files = NULL;int file_count = 0;+ int file_cap = 0;+ int64_t *seeds = NULL;+ int seed_count = 0;+ int seed_cap = 0;+ char line[CBM_SZ_1K];while (fgets(line, sizeof(line), fp)) {size_t len = strlen(line);while (len > 0 && (line[len - SKIP_ONE] == '\n' || line[len - SKIP_ONE] == '\r')) {@@@ -8499,35 -8848,199 +9795,228 @@@if (path_line[0] == '\0') {continue;}-- yyjson_mut_arr_add_strcpy(doc, changed, path_line);- file_count++;-+ /* Dedup: the three git sources are sorted+unioned on POSIX but not on+ * Windows (separate commands), and a path can repeat. */+ bool dup = false;+ for (int i = 0; i < file_count; i++) {+ if (strcmp(files[i], path_line) == 0) {+ dup = true;+ break;+ }+ }+ if (dup) {+ continue;+ }+ if (file_count >= file_cap) {+ file_cap = file_cap ? file_cap * 2 : 16;+ files = safe_realloc(files, (size_t)file_cap * sizeof(char *));+ }+ files[file_count++] = heap_strdup(path_line);if (want_symbols) {- detect_add_impacted_symbols(store, project, path_line, doc, impacted);+ detect_collect_seeds(store, project, path_line, &seeds, &seed_count, &seed_cap);}}- int git_status = cbm_pclose(fp);+ (void)fclose(fp);+ (void)cbm_unlink(output_path);+ int git_status = git_result.exit_code;- bool is_error = false;- if (git_status != 0 && file_count == 0) {- char hint_buf[CBM_SZ_256];- snprintf(hint_buf, sizeof(hint_buf),- "git diff exited with status %d. Check that branch '%s' exists.", git_status,+ /* merge-base SHA: the exact commit the diff is measured against, so the+ * result is reproducible even as base_branch advances. Best-effort. */+ char merge_base[64] = "";+ {+ char mbcmd[CBM_SZ_2K];+ #ifdef _WIN32+ snprintf(mbcmd, sizeof(mbcmd), "git -C \"%s\" merge-base \"%s\" HEAD 2>NUL", root_path,base_branch);- yyjson_mut_obj_add_strcpy(doc, root_obj, "hint", hint_buf);- is_error = true;+ #else+ snprintf(mbcmd, sizeof(mbcmd), "git -C '%s' merge-base '%s' HEAD 2>/dev/null", root_path,+ base_branch);+ #endif- FILE *mbfp = cbm_popen(mbcmd, "r");- if (mbfp) {++ char mb_output_path[CBM_SZ_2K] = {0};++ cbm_proc_result_t mb_result = {0};++ int mb_run = mcp_run_shell_command_cancellable(srv, mbcmd, mb_output_path, &mb_result);++ bool mb_cancelled = mb_result.cancellation_requested || mcp_request_cancelled(srv);++ bool mb_containment_failed = mb_run != 0 && mb_output_path[0] != '\0';++ FILE *mbfp =++ mb_run == 0 && mb_result.exit_code == 0 ? cbm_fopen(mb_output_path, "rb") : NULL;++ if (mbfp && !mb_cancelled) {+ if (fgets(merge_base, sizeof(merge_base), mbfp)) {+ size_t l = strlen(merge_base);+ while (l > 0 && (merge_base[l - 1] == '\n' || merge_base[l - 1] == '\r')) {+ merge_base[--l] = '\0';+ }+ }- (void)cbm_pclose(mbfp);++ }++ if (mbfp) {++ (void)fclose(mbfp);++ }++ if (mb_output_path[0]) {++ (void)cbm_unlink(mb_output_path);++ }++ if (mb_cancelled || mb_containment_failed) {++ for (int i = 0; i < file_count; i++) {++ free(files[i]);++ }++ free(files);++ free(seeds);++ free(direction);++ free(root_path);++ free(project);++ free(base_branch);++ free(scope);++ return cbm_mcp_text_result(++ mb_cancelled ? "detect_changes cancelled for this request"++ : "git merge-base failed: the contained command could not complete",++ true);+ }}- yyjson_mut_obj_add_val(doc, root_obj, "changed_files", changed);- yyjson_mut_obj_add_int(doc, root_obj, "changed_count", file_count);- yyjson_mut_obj_add_val(doc, root_obj, "impacted_symbols", impacted);- yyjson_mut_obj_add_int(doc, root_obj, "depth", depth);+ /* The impact traversal: ONE multi-source BFS over all seeds. */+ cbm_traverse_result_t impact = {0};+ bool truncated = false;+ if (want_symbols && seed_count > 0) {+ (void)cbm_store_bfs_multi(store, seeds, seed_count, direction, NULL, 0, depth,+ MCP_BFS_LIMIT_MAX, &impact, &truncated);+ }- char *json = yy_doc_to_str(doc);- yyjson_mut_doc_free(doc);+ bool is_error = (git_status != 0 && file_count == 0);+ char *out_str = NULL;++ if (!legacy_json) {+ cbm_sb_t sb;+ cbm_sb_init(&sb);+ cbm_tree_scalar_str(&sb, "base", base_branch);+ if (merge_base[0]) {+ cbm_tree_scalar_str(&sb, "merge_base", merge_base);+ }+ cbm_tree_scalar_str(&sb, "direction", direction);+ if (is_error) {+ char hint_buf[CBM_SZ_256];+ snprintf(hint_buf, sizeof(hint_buf),+ "git diff exited with status %d. Check that branch '%s' exists.", git_status,+ base_branch);+ cbm_tree_scalar_str(&sb, "hint", hint_buf);+ }+ /* changed files (the git result) */+ char cf[CBM_SZ_64];+ snprintf(cf, sizeof(cf), "changed_files: %d\n", file_count);+ cbm_sb_append(&sb, cf);+ for (int i = 0; i < file_count; i++) {+ cbm_sb_append(&sb, " ");+ cbm_sb_append(&sb, files[i]);+ cbm_sb_append(&sb, "\n");+ }+ cbm_tree_scalar_int(&sb, "seed_symbols", seed_count);+ if (want_symbols) {+ detect_emit_impacted_tree(&sb, &impact, imp_limit);+ /* module rollup: a quotient view of the blast radius */+ if (impact.visited_count > 0) {+ cbm_sb_append(&sb, "impacted_modules: (rows: module count)\n");+ char (*mods)[CBM_SZ_128] = malloc(DETECT_MODCAP * CBM_SZ_128);+ int *mcnt = malloc(DETECT_MODCAP * sizeof(int));+ if (mods && mcnt) {+ int overflow = 0;+ int nmods = detect_module_rollup(&impact, mods, mcnt, &overflow);+ for (int j = 0; j < nmods; j++) {+ char mrow[CBM_SZ_256];+ snprintf(mrow, sizeof(mrow), " %s %d\n", mods[j], mcnt[j]);+ cbm_sb_append(&sb, mrow);+ }+ if (overflow > 0) {+ char orow[CBM_SZ_128];+ snprintf(orow, sizeof(orow), " (other) %d\n", overflow);+ cbm_sb_append(&sb, orow);+ }+ }+ free(mods);+ free(mcnt);+ }+ if (truncated) {+ cbm_tree_scalar_bool(&sb, "truncated", true);+ cbm_tree_scalar_str(&sb, "hint",+ "impact hit the safety ceiling — narrow with a lower "+ "'depth' or a smaller diff");+ }+ }+ out_str = cbm_sb_finish(&sb);+ } else {+ /* format:"json" = json-stringified tree: same model, structured. */+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root_obj = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root_obj);+ yyjson_mut_obj_add_strcpy(doc, root_obj, "base", base_branch);+ if (merge_base[0]) {+ yyjson_mut_obj_add_strcpy(doc, root_obj, "merge_base", merge_base);+ }+ yyjson_mut_obj_add_strcpy(doc, root_obj, "direction", direction);+ yyjson_mut_val *cf = yyjson_mut_arr(doc);+ for (int i = 0; i < file_count; i++) {+ yyjson_mut_arr_add_strcpy(doc, cf, files[i]);+ }+ yyjson_mut_obj_add_val(doc, root_obj, "changed_files", cf);+ yyjson_mut_obj_add_int(doc, root_obj, "seed_symbols", seed_count);+ yyjson_mut_obj_add_int(doc, root_obj, "impacted_total", impact.visited_count);+ int imp_shown = impact.visited_count < imp_limit ? impact.visited_count : imp_limit;+ yyjson_mut_obj_add_int(doc, root_obj, "impacted_shown", imp_shown);+ yyjson_mut_val *imp = yyjson_mut_arr(doc);+ for (int i = 0; i < imp_shown; i++) {+ yyjson_mut_val *o = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_strcpy(+ doc, o, "qn",+ impact.visited[i].node.qualified_name ? impact.visited[i].node.qualified_name : "");+ yyjson_mut_obj_add_strcpy(+ doc, o, "label", impact.visited[i].node.label ? impact.visited[i].node.label : "");+ yyjson_mut_obj_add_strcpy(+ doc, o, "file",+ impact.visited[i].node.file_path ? impact.visited[i].node.file_path : "");+ yyjson_mut_obj_add_int(doc, o, "hop", impact.visited[i].hop);+ yyjson_mut_arr_add_val(imp, o);+ }+ yyjson_mut_obj_add_val(doc, root_obj, "impacted", imp);+ /* Model parity with the tree encoding: the complete module rollup. */+ if (impact.visited_count > 0) {+ char (*mods)[CBM_SZ_128] = malloc(DETECT_MODCAP * CBM_SZ_128);+ int *mcnt = malloc(DETECT_MODCAP * sizeof(int));+ if (mods && mcnt) {+ int overflow = 0;+ int nmods = detect_module_rollup(&impact, mods, mcnt, &overflow);+ yyjson_mut_val *rollup = yyjson_mut_arr(doc);+ for (int j = 0; j < nmods; j++) {+ yyjson_mut_val *o = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_strcpy(doc, o, "module", mods[j]);+ yyjson_mut_obj_add_int(doc, o, "count", mcnt[j]);+ yyjson_mut_arr_add_val(rollup, o);+ }+ if (overflow > 0) {+ yyjson_mut_val *o = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_strcpy(doc, o, "module", "(other)");+ yyjson_mut_obj_add_int(doc, o, "count", overflow);+ yyjson_mut_arr_add_val(rollup, o);+ }+ yyjson_mut_obj_add_val(doc, root_obj, "impacted_modules", rollup);+ }+ free(mods);+ free(mcnt);+ }+ yyjson_mut_obj_add_bool(doc, root_obj, "truncated", truncated);+ if (is_error) {+ char hint_buf[CBM_SZ_256];+ snprintf(hint_buf, sizeof(hint_buf),+ "git diff exited with status %d. Check that branch '%s' exists.", git_status,+ base_branch);+ yyjson_mut_obj_add_strcpy(doc, root_obj, "hint", hint_buf);+ }+ out_str = yy_doc_to_str(doc);+ yyjson_mut_doc_free(doc);+ }++ cbm_store_traverse_free(&impact);+ for (int i = 0; i < file_count; i++) {+ free(files[i]);+ }+ free(files);+ free(seeds);+ free(direction);free(root_path);free(project);free(base_branch);diff --cc src/mcp/mcp_internal.hindex 8547a8f4c,000000000..213159695mode 100644,000000..100644--- a/src/mcp/mcp_internal.h+++ b/src/mcp/mcp_internal.h@@@ -1,31 -1,0 +1,34 @@@+#ifndef CBM_MCP_INTERNAL_H+#define CBM_MCP_INTERNAL_H++#include "mcp/mcp.h"++/* White-box fault injection for deterministic cross-platform quarantine+ * safety tests. This header is internal and is not part of the MCP API. */+typedef bool (*cbm_mcp_quarantine_test_hook_fn)(void *context, const char *step);++typedef bool (*cbm_mcp_command_test_hook_fn)(void *context, const char *command);++void cbm_mcp_server_set_quarantine_test_hook(cbm_mcp_server_t *srv,+ cbm_mcp_quarantine_test_hook_fn hook, void *context);++void cbm_mcp_server_set_command_test_hook(cbm_mcp_server_t *srv, cbm_mcp_command_test_hook_fn hook,++ void *context);++/* Release only the constructor-created pristine in-memory store. Public+ * cbm_mcp_server_new(NULL) semantics remain unchanged; daemon sessions use+ * this immediately before publication so idle sessions retain no SQLite DB. */+bool cbm_mcp_server_release_pristine_memory_store(cbm_mcp_server_t *srv);++/* Prepend one daemon-owned notice to a successful JSON-RPC tool response.+ * On success replaces and frees *response_io; on failure it is unchanged. */+bool cbm_mcp_jsonrpc_response_prepend_notice(char **response_io, const char *notice);++enum { CBM_MCP_DEFAULT_AUTO_INDEX_LIMIT = 50000 };++/* Count indexable files with the pipeline's native full-mode discovery policy,+ * without retaining per-file results. A false result means the count exceeded+ * file_limit or could not be established before the bounded deadline; every+ * such failure is fail-closed because this is the memory-admission guard. */+bool cbm_mcp_auto_index_within_file_limit(const char *root_path, int file_limit,+ int *file_count_out);++#endifdiff --cc tests/test_cli.cindex cd517b72f,c6d72757d..6f95b1a6b--- a/tests/test_cli.c+++ b/tests/test_cli.c@@@ -14,11 -13,7 +14,12 @@@#include "test_framework.h"#include "test_helpers.h"#include <cli/cli.h>+#include <cli/progress_sink.h>+#include <daemon/bootstrap.h>+#include <daemon/runtime.h>+#include <daemon/version_cohort.h>+#include <foundation/platform.h>+ #include <mcp/mcp.h>#include <foundation/yaml.h>#include <store/store.h>#include <yyjson/yyjson.h>diff --cc tests/test_mcp.cindex a0fd45430,82b5469eb..8a38378d3--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@@ -125,299 -116,6 +125,335 @@@ static void cleanup_project_db(const chcbm_unlink(path);}+#define MCP_MUTATION_GUARD_MAX_EVENTS 16++typedef struct {+ int deny_begin_call; /* one-based; zero allows every acquisition */+ int cancel_on_begin_call; /* one-based; zero never requests cancellation */+ int begin_count;+ int end_count;+ cbm_mcp_server_t *cancel_server;+ bool cancel_attempted;+ bool cancel_accepted;+ const char *observed_db_path;+ const char *observed_backup_path;+ bool db_exists_at_begin;+ bool backup_exists_at_begin;+ bool db_exists_at_end;+ bool backup_exists_at_end;+ char begin_projects[MCP_MUTATION_GUARD_MAX_EVENTS][CBM_SZ_256];+ char end_projects[MCP_MUTATION_GUARD_MAX_EVENTS][CBM_SZ_256];+} mcp_mutation_guard_probe_t;++typedef struct {+ const char *deny_step;+ int call_count;+ char steps[4][64];+} mcp_quarantine_hook_probe_t;+++typedef struct {++ bool reject_merge_base;++ int diff_calls;++ int merge_base_calls;++} mcp_command_hook_probe_t;+++static bool mcp_quarantine_hook_probe(void *context, const char *step) {+ mcp_quarantine_hook_probe_t *probe = context;+ if (!probe || !step) {+ return false;+ }+ int event = probe->call_count++;+ if (event >= 0 && event < 4) {+ snprintf(probe->steps[event], sizeof(probe->steps[event]), "%s", step);+ }+ return !probe->deny_step || strcmp(probe->deny_step, step) != 0;+}+++static bool mcp_command_hook_probe(void *context, const char *command) {++ mcp_command_hook_probe_t *probe = context;++ if (!probe || !command) {++ return false;++ }++ if (strstr(command, "merge-base")) {++ probe->merge_base_calls++;++ return !probe->reject_merge_base;++ }++ probe->diff_calls++;++ return true;++}+++static bool mcp_mutation_guard_probe_begin(void *context, const char *project) {+ mcp_mutation_guard_probe_t *probe = context;+ if (!probe) {+ return false;+ }++ int event = probe->begin_count++;+ if (event < MCP_MUTATION_GUARD_MAX_EVENTS) {+ snprintf(probe->begin_projects[event], sizeof(probe->begin_projects[event]), "%s",+ project ? project : "");+ }+ if (probe->cancel_on_begin_call > 0 && probe->begin_count == probe->cancel_on_begin_call) {+ probe->cancel_attempted = true;+ probe->cancel_accepted = cbm_mcp_server_cancel_active(probe->cancel_server);+ }+ if (probe->observed_db_path) {+ probe->db_exists_at_begin = cbm_file_exists(probe->observed_db_path);+ }+ if (probe->observed_backup_path) {+ probe->backup_exists_at_begin = cbm_file_exists(probe->observed_backup_path);+ }+ return probe->deny_begin_call == 0 || probe->begin_count != probe->deny_begin_call;+}++static void mcp_mutation_guard_probe_end(void *context, const char *project) {+ mcp_mutation_guard_probe_t *probe = context;+ if (!probe) {+ return;+ }++ int event = probe->end_count++;+ if (event < MCP_MUTATION_GUARD_MAX_EVENTS) {+ snprintf(probe->end_projects[event], sizeof(probe->end_projects[event]), "%s",+ project ? project : "");+ }+ if (probe->observed_db_path) {+ probe->db_exists_at_end = cbm_file_exists(probe->observed_db_path);+ }+ if (probe->observed_backup_path) {+ probe->backup_exists_at_end = cbm_file_exists(probe->observed_backup_path);+ }+}++static bool mcp_make_corrupt_project_store(const char *cache, const char *project) {+ char db_path[CBM_SZ_1K];+ snprintf(db_path, sizeof(db_path), "%s/%s.db", cache, project);+ cbm_store_t *store = cbm_store_open_path(db_path);+ if (!store) {+ return false;+ }++ /* Numeric root paths are the deterministic corruption trigger used by+ * cbm_store_check_integrity() and the issue #557 reproduction. */+ bool created = cbm_store_upsert_project(store, project, "826") == CBM_STORE_OK;+ cbm_store_close(store);+ return created;+}++/* Keep a writer open so the fixture has a real, committed WAL generation.+ * Query-only opens must not alter either file when quarantine is denied or+ * cannot be published safely. The caller owns the returned store. */+static cbm_store_t *mcp_open_corrupt_project_store_with_wal(const char *cache,+ const char *project) {+ char db_path[CBM_SZ_1K];+ snprintf(db_path, sizeof(db_path), "%s/%s.db", cache, project);+ cbm_store_t *store = cbm_store_open_path(db_path);+ if (!store) {+ return NULL;+ }++ bool ready =+ cbm_store_exec(store, "PRAGMA wal_autocheckpoint=0;") == CBM_STORE_OK &&+ cbm_store_upsert_project(store, project, "826") == CBM_STORE_OK &&+ cbm_store_exec(store, "CREATE TABLE IF NOT EXISTS guard_wal_sentinel(value TEXT);"+ "INSERT INTO guard_wal_sentinel(value) VALUES('committed');") ==+ CBM_STORE_OK;+ if (!ready) {+ cbm_store_close(store);+ return NULL;+ }+ return store;+}++static bool mcp_make_valid_project_store_at(const char *path, const char *project,+ const char *root_path) {+ cbm_store_t *store = cbm_store_open_path(path);+ if (!store) {+ return false;+ }+ bool ready = cbm_store_upsert_project(store, project, root_path) == CBM_STORE_OK &&+ cbm_store_prepare_for_publish(store) == CBM_STORE_OK;+ cbm_store_close(store);+ return ready;+}++static unsigned char *mcp_read_file_bytes(const char *path, long *out_len) {+ if (!out_len) {+ return NULL;+ }+ *out_len = 0;+ FILE *fp = cbm_fopen(path, "rb");+ if (!fp) {+ return NULL;+ }+ if (fseek(fp, 0, SEEK_END) != 0) {+ fclose(fp);+ return NULL;+ }+ long size = ftell(fp);+ if (size < 0 || fseek(fp, 0, SEEK_SET) != 0) {+ fclose(fp);+ return NULL;+ }+ unsigned char *bytes = malloc(size > 0 ? (size_t)size : 1);+ if (!bytes) {+ fclose(fp);+ return NULL;+ }+ size_t read_count = fread(bytes, 1, (size_t)size, fp);+ fclose(fp);+ if (read_count != (size_t)size) {+ free(bytes);+ return NULL;+ }+ *out_len = size;+ return bytes;+}++static bool mcp_file_matches_snapshot(const char *path, const unsigned char *expected,+ long expected_len) {+ long actual_len = 0;+ unsigned char *actual = mcp_read_file_bytes(path, &actual_len);+ bool matches = actual && expected && actual_len == expected_len &&+ memcmp(actual, expected, (size_t)actual_len) == 0;+ free(actual);+ return matches;+}++/* Return the number of quarantine files for a project and, when present, the+ * first path whose name is distinct from the legacy fixed `.corrupt` name. */+static bool mcp_is_corrupt_backup_main_name(const char *name, const char *prefix) {+ size_t prefix_len = strlen(prefix);+ if (strcmp(name, prefix) == 0) {+ return true;+ }+ const char *suffix = name + prefix_len;+ if (strncmp(name, prefix, prefix_len) != 0 || suffix[0] != '.' || strlen(suffix + 1) != 16) {+ return false;+ }+ for (const char *cursor = suffix + 1; *cursor; cursor++) {+ if (!isxdigit((unsigned char)*cursor)) {+ return false;+ }+ }+ return true;+}++static int mcp_find_corrupt_backups(const char *cache, const char *project, char *unique_path,+ size_t unique_path_size) {+ if (unique_path && unique_path_size > 0) {+ unique_path[0] = '\0';+ }+ char prefix[CBM_DIRENT_NAME_MAX];+ snprintf(prefix, sizeof(prefix), "%s.db.corrupt", project);+ int count = 0;+ cbm_dir_t *dir = cbm_opendir(cache);+ if (!dir) {+ return 0;+ }+ cbm_dirent_t *entry;+ while ((entry = cbm_readdir(dir)) != NULL) {+ if (!mcp_is_corrupt_backup_main_name(entry->name, prefix)) {+ continue;+ }+ char path[CBM_SZ_1K];+ snprintf(path, sizeof(path), "%s/%s", cache, entry->name);+ if (!cbm_file_exists(path)) {+ continue;+ }+ count++;+ if (unique_path && unique_path_size > 0 && unique_path[0] == '\0' &&+ strcmp(entry->name, prefix) != 0) {+ snprintf(unique_path, unique_path_size, "%s", path);+ }+ }+ cbm_closedir(dir);+ return count;+}++static int mcp_count_corrupt_artifacts(const char *cache, const char *project) {+ char prefix[CBM_DIRENT_NAME_MAX];+ snprintf(prefix, sizeof(prefix), "%s.db.corrupt", project);+ size_t prefix_len = strlen(prefix);+ int count = 0;+ cbm_dir_t *dir = cbm_opendir(cache);+ if (!dir) {+ return 0;+ }+ cbm_dirent_t *entry;+ while ((entry = cbm_readdir(dir)) != NULL) {+ if (strncmp(entry->name, prefix, prefix_len) == 0) {+ count++;+ }+ }+ cbm_closedir(dir);+ return count;+}+++static int mcp_count_directory_entries_with_prefix(const char *directory, const char *prefix) {++ cbm_dir_t *dir = cbm_opendir(directory);++ if (!dir) {++ return -1;++ }++ size_t prefix_length = strlen(prefix);++ int count = 0;++ cbm_dirent_t *entry;++ while ((entry = cbm_readdir(dir)) != NULL) {++ if (strncmp(entry->name, prefix, prefix_length) == 0) {++ count++;++ }++ }++ cbm_closedir(dir);++ return count;++}+++static void mcp_cleanup_corrupt_backups(const char *cache, const char *project) {+ char prefix[CBM_DIRENT_NAME_MAX];+ snprintf(prefix, sizeof(prefix), "%s.db.corrupt", project);+ size_t prefix_len = strlen(prefix);+ cbm_dir_t *dir = cbm_opendir(cache);+ if (!dir) {+ return;+ }+ cbm_dirent_t *entry;+ while ((entry = cbm_readdir(dir)) != NULL) {+ if (strncmp(entry->name, prefix, prefix_len) == 0) {+ char path[CBM_SZ_1K];+ snprintf(path, sizeof(path), "%s/%s", cache, entry->name);+ cbm_unlink(path);+ }+ }+ cbm_closedir(dir);+}++typedef struct {+ mcp_mutation_guard_probe_t guard;+ const char *replacement_path;+ const char *live_path;+ bool replacement_attempted;+ bool replacement_succeeded;+} mcp_replacing_mutation_guard_t;++static bool mcp_replacing_mutation_guard_begin(void *context, const char *project) {+ mcp_replacing_mutation_guard_t *replacement = context;+ if (!replacement || !mcp_mutation_guard_probe_begin(&replacement->guard, project)) {+ return false;+ }+ replacement->replacement_attempted = true;+ bool sidecars_removed = cbm_remove_db_sidecars(replacement->live_path) == 0;+ replacement->replacement_succeeded =+ sidecars_removed &&+ cbm_rename_replace(replacement->replacement_path, replacement->live_path) == 0;+ return true;+}++static void mcp_replacing_mutation_guard_end(void *context, const char *project) {+ mcp_replacing_mutation_guard_t *replacement = context;+ if (replacement) {+ mcp_mutation_guard_probe_end(&replacement->guard, project);+ }+}+/* ══════════════════════════════════════════════════════════════════* JSON-RPC PARSING* ══════════════════════════════════════════════════════════════════ */@@@ -5004,6 -4004,6 +5646,88 @@@ TEST(tool_detect_changes_not_found_richPASS();}++/* detect_changes owns shell output through regular temporary files. An error++ * after opening that file must use fclose + unlink. The command hook then++ * rejects merge-base only when it reaches the contained subprocess helper, so++ * a raw popen regression bypasses the hook and fails this test. */++TEST(tool_detect_changes_contained_commands_clean_up_error_and_success) {++ char cache[512];++ (void)snprintf(cache, sizeof(cache), "%s/cbm-detect-contained-XXXXXX", cbm_tmpdir());++ bool cache_created = cbm_mkdtemp(cache) != NULL;++ const char *saved_cache = getenv("CBM_CACHE_DIR");++ char *saved_cache_copy = saved_cache ? strdup(saved_cache) : NULL;++ bool environment_ready = cache_created && cbm_setenv("CBM_CACHE_DIR", cache, 1) == 0;++++ char root[CBM_SZ_4K] = {0};++ bool root_ready = cbm_getcwd(root, sizeof(root)) != NULL;++ const char *project = "detect-contained-project";++ cbm_mcp_server_t *srv = environment_ready && root_ready ? cbm_mcp_server_new(NULL) : NULL;++ bool server_ready = srv != NULL;++ cbm_store_t *store = srv ? cbm_mcp_server_store(srv) : NULL;++ bool project_ready = store && cbm_store_upsert_project(store, project, root) == CBM_STORE_OK;++ mcp_command_hook_probe_t command_probe = {.reject_merge_base = true};++ if (project_ready) {++ cbm_mcp_server_set_project(srv, project);++ cbm_mcp_server_set_command_test_hook(srv, mcp_command_hook_probe, &command_probe);++ }++++ char *invalid_response =++ project_ready ? cbm_mcp_handle_tool(srv, "detect_changes",++ "{\"project\":\"detect-contained-project\","++ "\"base_branch\":\"HEAD\",\"scope\":\"files\","++ "\"direction\":\"sideways\"}")++ : NULL;++ bool invalid_rejected = invalid_response && strstr(invalid_response, "invalid direction");++ char logs[640];++ (void)snprintf(logs, sizeof(logs), "%s/logs", cache);++ int artifacts_after_error =++ invalid_response ? mcp_count_directory_entries_with_prefix(logs, ".mcp-command-") : -1;++++ char *rejected_response =++ project_ready ? cbm_mcp_handle_tool(srv, "detect_changes",++ "{\"project\":\"detect-contained-project\","++ "\"base_branch\":\"HEAD\",\"scope\":\"files\"}")++ : NULL;++ bool containment_rejected =++ rejected_response && strstr(rejected_response, "contained command could not complete");++ int artifacts_after_rejection =++ rejected_response ? mcp_count_directory_entries_with_prefix(logs, ".mcp-command-") : -1;++++ command_probe.reject_merge_base = false;++ char *success_response =++ project_ready ? cbm_mcp_handle_tool(srv, "detect_changes",++ "{\"project\":\"detect-contained-project\","++ "\"base_branch\":\"HEAD\",\"scope\":\"files\"}")++ : NULL;++ bool merge_base_reported = success_response && strstr(success_response, "merge_base");++ int artifacts_after_success =++ success_response ? mcp_count_directory_entries_with_prefix(logs, ".mcp-command-") : -1;++++ free(invalid_response);++ free(rejected_response);++ free(success_response);++ cbm_mcp_server_free(srv);++ restore_cache_dir(saved_cache_copy);++ free(saved_cache_copy);++ bool cleaned = !cache_created || th_rmtree(cache) == 0;++++ ASSERT_TRUE(cache_created);++ ASSERT_TRUE(environment_ready);++ ASSERT_TRUE(root_ready);++ ASSERT_TRUE(server_ready);++ ASSERT_TRUE(project_ready);++ ASSERT_TRUE(invalid_rejected);++ ASSERT_EQ(artifacts_after_error, 0);++ ASSERT_TRUE(containment_rejected);++ ASSERT_EQ(artifacts_after_rejection, 0);++ ASSERT_TRUE(merge_base_reported);++ ASSERT_EQ(artifacts_after_success, 0);++ ASSERT_EQ(command_probe.diff_calls, 3);++ ASSERT_EQ(command_probe.merge_base_calls, 2);++ ASSERT_TRUE(cleaned);++ PASS();++}++TEST(tool_ingest_traces_basic) {cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);@@@ -8633,6 -7080,6 +9364,7 @@@ SUITE(mcp)RUN_TEST(tool_manage_adr_get_accepts_abs_path);RUN_TEST(tool_manage_adr_get_accepts_symlink_path);RUN_TEST(tool_detect_changes_not_found_rich_error);++ RUN_TEST(tool_detect_changes_contained_commands_clean_up_error_and_success);RUN_TEST(tool_ingest_traces_basic);RUN_TEST(tool_ingest_traces_empty);