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
fix(mcp): resolve repository default for detect_changes
Martin Vogel72f206d18fea
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex c877d5110..50ae72774 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -786,8 +786,8 @@ static const tool_def_t TOOLS[] = {"\"module_cursor\":{\"type\":\"string\"},""\"max_output_tokens\":{\"type\":\"integer\",\"default\":3200,\"minimum\":128,""\"maximum\":1000000,\"description\":\"Sizing hint; hard ceiling is 4 UTF-8 bytes/token.\"},"- "\"base_branch\":{\"type\":"- "\"string\",\"default\":\"main\"},\"since\":{\"type\":\"string\"},"+ "\"base_branch\":{\"type\":\"string\",\"description\":\"Default: origin/HEAD, else "+ "main, else master, else the upstream.\"},\"since\":{\"type\":\"string\"},""\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},""\"required\":""[\"project\"]}"},@@ -16021,6 +16021,92 @@ static bool detect_valid_object_id(const char *value) {return true;}+/* Run one contained git query and return its first output line. False when+ * the command fails, is cancelled, prints nothing, or prints a value that+ * cannot be spliced back into the later git commands safely. */+static bool detect_git_first_line(cbm_mcp_server_t *srv, const char *command, char *out,+ size_t out_size) {+ out[0] = '\0';+ char output_path[CBM_SZ_2K] = {0};+ cbm_proc_result_t result = {0};+ int run = mcp_run_shell_command_cancellable(srv, command, output_path, &result);+ bool ok = run == 0 && result.exit_code == 0 && !result.cancellation_requested &&+ !mcp_request_cancelled(srv);+ FILE *fp = ok ? cbm_fopen(output_path, "rb") : NULL;+ bool read = fp && fgets(out, (int)out_size, fp) != NULL;+ if (fp) {+ (void)fclose(fp);+ }+ if (output_path[0]) {+ (void)cbm_unlink(output_path);+ }+ size_t length = read ? strlen(out) : 0;+ /* A line that filled the buffer without its newline was truncated. */+ bool complete = length > 0 && out[length - 1] == '\n';+ while (length > 0 && (out[length - 1] == '\n' || out[length - 1] == '\r')) {+ out[--length] = '\0';+ }+ ok = ok && complete && length > 0 && out[0] != '-' && cbm_validate_shell_arg(out) &&+ validate_windows_cmd_interpolation_arg(out);+ if (!ok) {+ out[0] = '\0';+ }+ return ok;+}++/* #1357: without base_branch, diff against the repository's default branch+ * rather than a literal "main" that trunk/master/develop repositories do not+ * have. Order: origin/HEAD (what the clone calls the default), a local main,+ * a local master, then the current branch's upstream. main and master come+ * before the upstream on purpose: a pushed feature branch tracks its own+ * remote twin, and diffing against that would silently shrink the impact+ * analysis to unpushed commits. Nothing resolves -> false, out = "main", and+ * the caller reports that ref as the one it tried. */+static bool detect_default_base(cbm_mcp_server_t *srv, const char *root_path, char *out,+ size_t out_size) {+#ifdef _WIN32+#define DETECT_GIT_Q "\""+#define DETECT_GIT_NULL "2>NUL"+#else+#define DETECT_GIT_Q "'"+#define DETECT_GIT_NULL "2>/dev/null"+#endif+ char command[CBM_SZ_2K];+ char line[CBM_SZ_1K];+ snprintf(command, sizeof(command),+ "git -C " DETECT_GIT_Q "%s" DETECT_GIT_Q+ " symbolic-ref -q --short refs/remotes/origin/HEAD " DETECT_GIT_NULL,+ root_path);+ if (detect_git_first_line(srv, command, line, sizeof(line))) {+ snprintf(out, out_size, "%s", line);+ return true;+ }+ static const char *const local_defaults[] = {"main", "master"};+ for (size_t i = 0; i < sizeof(local_defaults) / sizeof(local_defaults[0]); i++) {+ snprintf(command, sizeof(command),+ "git -C " DETECT_GIT_Q "%s" DETECT_GIT_Q " rev-parse -q --verify " DETECT_GIT_Q+ "refs/heads/%s^{commit}" DETECT_GIT_Q " " DETECT_GIT_NULL,+ root_path, local_defaults[i]);+ if (detect_git_first_line(srv, command, line, sizeof(line))) {+ snprintf(out, out_size, "%s", local_defaults[i]);+ return true;+ }+ }+ snprintf(command, sizeof(command),+ "git -C " DETECT_GIT_Q "%s" DETECT_GIT_Q+ " rev-parse -q --abbrev-ref --symbolic-full-name " DETECT_GIT_Q+ "@{upstream}" DETECT_GIT_Q " " DETECT_GIT_NULL,+ root_path);+ if (detect_git_first_line(srv, command, line, sizeof(line))) {+ snprintf(out, out_size, "%s", line);+ return true;+ }+#undef DETECT_GIT_Q+#undef DETECT_GIT_NULL+ snprintf(out, out_size, "%s", "main");+ return false;+}+typedef struct {char stream; /* c=changed files, i=impacted symbols, m=module rollup */char snapshot[33]; /* first 128 bits of the SHA-256 live-state fingerprint */@@ -16267,17 +16353,17 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {}free(since); /* no-op after the swap (since is NULL); frees it otherwise */- if (!base_branch) {- base_branch = heap_strdup("main");- }+ /* No base given: resolved from the repository after the project root is+ * known (#1357). An explicit base_branch/since is used as given. */+ bool base_defaulted = base_branch == NULL;/* Reject shell metacharacters, and a leading '-', in the user-supplied* branch name. base_branch is spliced into `git diff --name-only* "<base>"...HEAD`; a value starting with '-' would be read by git as an* option rather than a ref (e.g. `--output=<path>` writes the diff to an* arbitrary file). A real git ref never begins with '-'. */- if (!cbm_validate_shell_arg(base_branch) || base_branch[0] == '-' ||- !validate_windows_cmd_interpolation_arg(base_branch)) {+ if (base_branch && (!cbm_validate_shell_arg(base_branch) || base_branch[0] == '-' ||+ !validate_windows_cmd_interpolation_arg(base_branch))) {free(project);free(base_branch);free(scope);@@ -16295,13 +16381,24 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {return res;}- if (!validate_search_path_arg(root_path) ||- !validate_windows_cmd_interpolation_arg(root_path)) {+ /* The default base is looked up only once root_path is known to be safe+ * to splice into the git command line. */+ bool root_ok =+ validate_search_path_arg(root_path) && validate_windows_cmd_interpolation_arg(root_path);+ bool default_base_found = true;+ if (root_ok && base_defaulted) {+ char default_base[CBM_SZ_1K];+ default_base_found =+ detect_default_base(srv, root_path, default_base, sizeof(default_base));+ base_branch = heap_strdup(default_base);+ }+ if (!root_ok || !base_branch) {free(root_path);free(project);free(base_branch);free(scope);- return cbm_mcp_text_result("project path contains invalid characters", true);+ return cbm_mcp_text_result(+ root_ok ? "out of memory" : "project path contains invalid characters", true);}/* Every detect snapshot and cursor is generation-bound. Validate the@@ -16391,6 +16488,25 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {}if (resolve_cancelled || resolve_run != 0 || resolve_result.exit_code != 0 || resolve_oom ||!head_oid[0] || !base_oid[0] || !git_prefix_valid) {+ /* Name the ref that was tried: a bare "not a commit" left callers of+ * the implicit default guessing which base was meant (#1357). */+ char resolve_error[CBM_SZ_2K];+ if (!base_defaulted) {+ snprintf(resolve_error, sizeof(resolve_error),+ "git revision resolution failed: base_branch \"%s\" or HEAD is not a commit",+ base_branch);+ } else if (!default_base_found) {+ snprintf(resolve_error, sizeof(resolve_error),+ "git revision resolution failed: no default base found (tried origin/HEAD, "+ "main, master and the upstream; fell back to \"%s\"), or HEAD is not a "+ "commit; pass base_branch",+ base_branch);+ } else {+ snprintf(resolve_error, sizeof(resolve_error),+ "git revision resolution failed: default base \"%s\" or HEAD is not a "+ "commit; pass base_branch",+ base_branch);+ }free(direction);free(root_path);free(project);@@ -16409,8 +16525,7 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {"worktree could not be determined",true);}- return cbm_mcp_text_result(- "git revision resolution failed: base_branch or HEAD is not a commit", true);+ return cbm_mcp_text_result(resolve_error, true);}char merge_base[65] = "";diff --git a/tests/test_mcp.c b/tests/test_mcp.cindex 22af972af..ed231574c 100644--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@ -14317,6 +14317,155 @@ TEST(tool_detect_changes_invalid_base_is_an_error) {PASS();}+/* #1357: detect_changes without base_branch must diff against the+ * repository's default branch, not a literal "main". Each fixture is a real+ * git repository: a base commit on the default branch, then a feature branch+ * with one committed file, so the correct base yields exactly that file. */+typedef struct {+ char repo[CBM_SZ_4K];+ char cache[CBM_SZ_4K];+ char base[CBM_SZ_256];+ bool is_error;+ bool feature_listed;+ char error_text[CBM_SZ_1K];+} detect_default_base_probe_t;++static bool detect_default_base_repo(const char *repo, const char *default_branch,+ bool set_origin_head) {+ char head_ref[CBM_SZ_256];+ snprintf(head_ref, sizeof(head_ref), "refs/heads/%s", default_branch);+ char remote_ref[CBM_SZ_256];+ snprintf(remote_ref, sizeof(remote_ref), "refs/remotes/origin/%s", default_branch);+ char base_file[CBM_SZ_4K];+ char feature_file[CBM_SZ_4K];+ snprintf(base_file, sizeof(base_file), "%s/base.c", repo);+ snprintf(feature_file, sizeof(feature_file), "%s/feature.c", repo);+ const char *const init_args[] = {"init", "-q", NULL};+ const char *const head_args[] = {"symbolic-ref", "HEAD", head_ref, NULL};+ const char *const add_base_args[] = {"add", "base.c", NULL};+ const char *const add_feature_args[] = {"add", "feature.c", NULL};+ const char *const commit_args[] = {+ "-c", "user.name=cbm-test",+ "-c", "[email protected]",+ "-c", "commit.gpgsign=false",+ "commit", "-q",+ "-m", "fixture",+ NULL,+ };+ const char *const remote_args[] = {"update-ref", remote_ref, "HEAD", NULL};+ const char *const origin_head_args[] = {"symbolic-ref", "refs/remotes/origin/HEAD", remote_ref,+ NULL};+ const char *const feature_args[] = {"checkout", "-q", "-b", "feature", NULL};+ bool ok = mcp_test_git(repo, init_args) == 0 && mcp_test_git(repo, head_args) == 0 &&+ th_write_file(base_file, "int base_value = 1;\n") == 0 &&+ mcp_test_git(repo, add_base_args) == 0 && mcp_test_git(repo, commit_args) == 0;+ if (ok && set_origin_head) {+ ok = mcp_test_git(repo, remote_args) == 0 && mcp_test_git(repo, origin_head_args) == 0;+ }+ return ok && mcp_test_git(repo, feature_args) == 0 &&+ th_write_file(feature_file, "int feature_value = 2;\n") == 0 &&+ mcp_test_git(repo, add_feature_args) == 0 && mcp_test_git(repo, commit_args) == 0;+}++static bool detect_default_base_run(const char *default_branch, bool set_origin_head,+ const char *base_arg, detect_default_base_probe_t *probe) {+ memset(probe, 0, sizeof(*probe));+ snprintf(probe->repo, sizeof(probe->repo), "%s/cbm-detect-default-XXXXXX", cbm_tmpdir());+ snprintf(probe->cache, sizeof(probe->cache), "%s/cbm-detect-default-cache-XXXXXX",+ cbm_tmpdir());+ if (!cbm_mkdtemp(probe->repo) || !cbm_mkdtemp(probe->cache) ||+ !detect_default_base_repo(probe->repo, default_branch, set_origin_head)) {+ return false;+ }+ const char *saved_cache = getenv("CBM_CACHE_DIR");+ char *saved_cache_copy = saved_cache ? strdup(saved_cache) : NULL;+ bool ok = cbm_setenv("CBM_CACHE_DIR", probe->cache, 1) == 0;+ cbm_mcp_server_t *srv = ok ? cbm_mcp_server_new(NULL) : NULL;+ cbm_store_t *store = srv ? cbm_mcp_server_store(srv) : NULL;+ const char *project = "detect-default-base-project";+ ok = store && cbm_store_upsert_project(store, project, probe->repo) == CBM_STORE_OK;+ char args[CBM_SZ_1K];+ if (base_arg) {+ snprintf(args, sizeof(args),+ "{\"project\":\"%s\",\"base_branch\":\"%s\",\"scope\":\"files\","+ "\"format\":\"json\"}",+ project, base_arg);+ } else {+ snprintf(args, sizeof(args), "{\"project\":\"%s\",\"scope\":\"files\",\"format\":\"json\"}",+ project);+ }+ if (ok) {+ cbm_mcp_server_set_project(srv, project);+ }+ char *response = ok ? cbm_mcp_handle_tool(srv, "detect_changes", args) : NULL;+ char *inner = response ? extract_text_content(response) : NULL;+ probe->is_error = response && response_contains_json_fragment(response, "\"isError\":true");+ if (inner && probe->is_error) {+ snprintf(probe->error_text, sizeof(probe->error_text), "%s", inner);+ }+ yyjson_doc *doc = inner && !probe->is_error ? yyjson_read(inner, strlen(inner), 0) : NULL;+ yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL;+ const char *base = root ? yyjson_get_str(yyjson_obj_get(root, "base")) : NULL;+ if (base) {+ snprintf(probe->base, sizeof(probe->base), "%s", base);+ }+ yyjson_val *changed = root ? yyjson_obj_get(root, "changed_files") : NULL;+ size_t index;+ size_t count;+ yyjson_val *entry;+ yyjson_arr_foreach(changed, index, count, entry) {+ if (yyjson_is_str(entry) && strcmp(yyjson_get_str(entry), "feature.c") == 0) {+ probe->feature_listed = true;+ }+ }+ yyjson_doc_free(doc);+ free(inner);+ free(response);+ if (srv) {+ cbm_mcp_server_free(srv);+ }+ restore_cache_dir(saved_cache_copy);+ free(saved_cache_copy);+ bool cleaned = th_rmtree(probe->cache) == 0 && th_rmtree(probe->repo) == 0;+ return ok && cleaned;+}++TEST(detect_changes_default_base_follows_origin_head_issue1357) {+ detect_default_base_probe_t probe;+ ASSERT_TRUE(detect_default_base_run("trunk", true, NULL, &probe));+ ASSERT_FALSE(probe.is_error);+ ASSERT_STR_EQ(probe.base, "origin/trunk");+ ASSERT_TRUE(probe.feature_listed);+ PASS();+}++TEST(detect_changes_default_base_falls_back_to_master_issue1357) {+ detect_default_base_probe_t probe;+ ASSERT_TRUE(detect_default_base_run("master", false, NULL, &probe));+ ASSERT_FALSE(probe.is_error);+ ASSERT_STR_EQ(probe.base, "master");+ ASSERT_TRUE(probe.feature_listed);+ PASS();+}++TEST(detect_changes_explicit_base_is_used_as_given_issue1357) {+ detect_default_base_probe_t probe;+ ASSERT_TRUE(detect_default_base_run("trunk", true, "trunk", &probe));+ ASSERT_FALSE(probe.is_error);+ ASSERT_STR_EQ(probe.base, "trunk");+ ASSERT_TRUE(probe.feature_listed);+ PASS();+}++TEST(detect_changes_unresolvable_default_names_tried_ref_issue1357) {+ detect_default_base_probe_t probe;+ ASSERT_TRUE(detect_default_base_run("develop", false, NULL, &probe));+ ASSERT_TRUE(probe.is_error);+ ASSERT_NOT_NULL(strstr(probe.error_text, "\"main\""));+ ASSERT_NOT_NULL(strstr(probe.error_text, "origin/HEAD"));+ PASS();+}+TEST(tool_detect_changes_preserves_utf8_git_path_and_impact_seed) {char repo[CBM_SZ_4K];snprintf(repo, sizeof(repo), "%s/cbm-detect-utf8-path-XXXXXX", cbm_tmpdir());@@ -21289,6 +21438,10 @@ SUITE(mcp) {RUN_TEST(tool_manage_adr_get_accepts_symlink_path);RUN_TEST(tool_detect_changes_not_found_rich_error);RUN_TEST(tool_detect_changes_invalid_base_is_an_error);+ RUN_TEST(detect_changes_default_base_follows_origin_head_issue1357);+ RUN_TEST(detect_changes_default_base_falls_back_to_master_issue1357);+ RUN_TEST(detect_changes_explicit_base_is_used_as_given_issue1357);+ RUN_TEST(detect_changes_unresolvable_default_names_tried_ref_issue1357);RUN_TEST(tool_detect_changes_preserves_utf8_git_path_and_impact_seed);RUN_TEST(tool_detect_changes_finds_nested_untracked_file_and_impact_seed);RUN_TEST(tool_detect_changes_subdirectory_project_translates_git_root_paths_issue1951);