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(git): clear git's repository-local env for cbm's own git children (#2003)
Martin Vogel40dad610eec7
diff --git a/Makefile.cbm b/Makefile.cbmindex 305cb6937..ce0538718 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -327,6 +327,7 @@ FOUNDATION_SRCS = \src/foundation/limits.c \src/foundation/index_policy.c \src/foundation/subprocess.c \+ src/foundation/git_env.c \src/foundation/sha256.c \src/foundation/secure_random.c \src/foundation/macos_acl.c \diff --git a/src/foundation/compat_fs.c b/src/foundation/compat_fs.cindex 71ab16b11..604faa50f 100644--- a/src/foundation/compat_fs.c+++ b/src/foundation/compat_fs.c@@ -7,6 +7,7 @@#include "foundation/constants.h"#include "foundation/compat_fs.h"#include "foundation/compat_fs_internal.h"+#include "foundation/git_env.h"#include <stdio.h>#include <stdlib.h>@@ -236,7 +237,9 @@ static wchar_t *cbm_resolve_comspec(void) {/* On failure returns NULL with *stage naming the failing step and *gle the* GetLastError value captured at that step (0 when errno is the signal). */-static FILE *cbm_popen_isolated(const char *cmd, const char **stage, DWORD *gle) {+/* env: a CREATE_UNICODE_ENVIRONMENT block for the child, or NULL to inherit. */+static FILE *cbm_popen_isolated(const char *cmd, const wchar_t *env, const char **stage,+ DWORD *gle) {*stage = "";*gle = 0;InitOnceExecuteOnce(&g_popen_once, cbm_popen_init, NULL, NULL);@@ -315,8 +318,11 @@ static FILE *cbm_popen_isolated(const char *cmd, const char **stage, DWORD *gle)*stage = "cmdline";*gle = ERROR_NOT_ENOUGH_MEMORY;} else {- created = CreateProcessW(app, wcmdline, NULL, NULL, TRUE,- EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, NULL, NULL,+ DWORD flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW;+ if (env) {+ flags |= CREATE_UNICODE_ENVIRONMENT;+ }+ created = CreateProcessW(app, wcmdline, NULL, NULL, TRUE, flags, (LPVOID)env, NULL,&si.StartupInfo, &pi);if (!created) {*stage = "spawn";@@ -372,29 +378,46 @@ static FILE *cbm_popen_isolated(const char *cmd, const char **stage, DWORD *gle)return NULL;}+static FILE *cbm_popen_read_isolated(const char *cmd, const wchar_t *env) {+ const char *stage = "";+ DWORD gle = 0;+ FILE *fp = cbm_popen_isolated(cmd, env, &stage, &gle);+ g_popen_last_isolated = (fp != NULL);+ if (!fp) {+ char glebuf[CBM_SZ_16];+ char errnobuf[CBM_SZ_16];+ snprintf(glebuf, sizeof(glebuf), "%lu", (unsigned long)gle);+ snprintf(errnobuf, sizeof(errnobuf), "%d", errno);+ cbm_log_warn("compat.popen_isolated_failed", "stage", stage, "gle", glebuf, "errno",+ errnobuf);+ }+ return fp;+}+FILE *cbm_popen(const char *cmd, const char *mode) {/* Our git shell-outs are all read-mode; they MUST use the isolated* spawn. On failure, log and fail the call — never fall back to* _popen, whose full handle inheritance re-arms the UI hang (#798). */if (mode && mode[0] == 'r' && mode[1] == '\0') {- const char *stage = "";- DWORD gle = 0;- FILE *fp = cbm_popen_isolated(cmd, &stage, &gle);- g_popen_last_isolated = (fp != NULL);- if (!fp) {- char glebuf[CBM_SZ_16];- char errnobuf[CBM_SZ_16];- snprintf(glebuf, sizeof(glebuf), "%lu", (unsigned long)gle);- snprintf(errnobuf, sizeof(errnobuf), "%d", errno);- cbm_log_warn("compat.popen_isolated_failed", "stage", stage, "gle", glebuf, "errno",- errnobuf);- }- return fp;+ return cbm_popen_read_isolated(cmd, NULL);}g_popen_last_isolated = 0;return _popen(cmd, mode);}+FILE *cbm_popen_git(const char *cmd) {+ /* Fail closed: without the scrubbed block the child would inherit a+ * caller's GIT_DIR and read the wrong repository (#2003). */+ wchar_t *env = cbm_git_child_env_block();+ if (!env) {+ cbm_log_warn("compat.popen_git_env_failed", "stage", "env_block");+ return NULL;+ }+ FILE *fp = cbm_popen_read_isolated(cmd, env);+ cbm_git_child_env_free(env); /* CreateProcessW copies the block into the child */+ return fp;+}+int cbm_pclose(FILE *f) {InitOnceExecuteOnce(&g_popen_once, cbm_popen_init, NULL, NULL);@@ -759,6 +782,8 @@ int cbm_exec_no_shell(const char *const *argv) {#include <dirent.h>#include <errno.h>#include <fcntl.h>+#include <pthread.h>+#include <spawn.h>#include <sys/file.h>#include <sys/stat.h>#include <sys/wait.h>@@ -863,8 +888,119 @@ FILE *cbm_popen(const char *cmd, const char *mode) {return popen(cmd, mode);}+/* Streams opened by cbm_popen_git: popen() cannot take an environment, so+ * those children are spawned here and reaped by cbm_pclose via this list. */+typedef struct cbm_popen_git_entry {+ FILE *fp;+ pid_t pid;+ struct cbm_popen_git_entry *next;+} cbm_popen_git_entry_t;++static cbm_popen_git_entry_t *g_popen_git_list = NULL;+static pthread_mutex_t g_popen_git_lock = PTHREAD_MUTEX_INITIALIZER;++static bool cbm_fd_set_cloexec(int fd) {+ int flags = fcntl(fd, F_GETFD);+ return flags >= 0 && fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0;+}++/* `/bin/sh -c cmd` with stdout on a pipe, stdin on /dev/null (never the MCP+ * transport), stderr inherited like popen(), and `envp` as the environment. */+static pid_t cbm_popen_spawn_sh(const char *cmd, char **envp, int *read_fd) {+ int fds[2];+ if (pipe(fds) != 0) {+ return -1;+ }+ if (!cbm_fd_set_cloexec(fds[0]) || !cbm_fd_set_cloexec(fds[1])) {+ (void)close(fds[0]);+ (void)close(fds[1]);+ return -1;+ }+ posix_spawn_file_actions_t actions;+ if (posix_spawn_file_actions_init(&actions) != 0) {+ (void)close(fds[0]);+ (void)close(fds[1]);+ return -1;+ }+ /* dup2 clears close-on-exec on the child's stdout; both pipe ends+ * themselves stay close-on-exec, so no other child ever holds them. */+ bool configured =+ posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0) == 0 &&+ posix_spawn_file_actions_adddup2(&actions, fds[1], STDOUT_FILENO) == 0;+ char *const argv[] = {(char *)"sh", (char *)"-c", (char *)cmd, NULL};+ pid_t pid = -1;+ int rc = configured ? posix_spawn(&pid, "/bin/sh", &actions, NULL, argv, envp) : -1;+ (void)posix_spawn_file_actions_destroy(&actions);+ (void)close(fds[1]);+ if (rc != 0 || pid <= 0) {+ (void)close(fds[0]);+ return -1;+ }+ *read_fd = fds[0];+ return pid;+}++static int cbm_popen_git_wait(pid_t pid) {+ int status = 0;+ while (waitpid(pid, &status, 0) < 0) {+ if (errno != EINTR) {+ return -1;+ }+ }+ return status;+}++FILE *cbm_popen_git(const char *cmd) {+ if (!cmd) {+ return NULL;+ }+ /* Fail closed: without the scrubbed environment the child would inherit+ * a caller's GIT_DIR and read the wrong repository (#2003). */+ char **envp = cbm_git_child_envp();+ if (!envp) {+ return NULL;+ }+ int read_fd = -1;+ pid_t pid = cbm_popen_spawn_sh(cmd, envp, &read_fd);+ cbm_git_child_env_free(envp); /* posix_spawn copied it into the child */+ if (pid < 0) {+ return NULL;+ }+ cbm_popen_git_entry_t *entry = (cbm_popen_git_entry_t *)malloc(sizeof(*entry));+ FILE *fp = entry ? fdopen(read_fd, "r") : NULL;+ if (!fp) {+ free(entry);+ (void)close(read_fd);+ (void)cbm_popen_git_wait(pid);+ return NULL;+ }+ entry->fp = fp;+ entry->pid = pid;+ pthread_mutex_lock(&g_popen_git_lock);+ entry->next = g_popen_git_list;+ g_popen_git_list = entry;+ pthread_mutex_unlock(&g_popen_git_lock);+ return fp;+}+int cbm_pclose(FILE *f) {- return pclose(f);+ cbm_popen_git_entry_t *found = NULL;+ pthread_mutex_lock(&g_popen_git_lock);+ for (cbm_popen_git_entry_t **link = &g_popen_git_list; *link; link = &(*link)->next) {+ if ((*link)->fp == f) {+ found = *link;+ *link = found->next;+ break;+ }+ }+ pthread_mutex_unlock(&g_popen_git_lock);+ if (!found) {+ return pclose(f); /* opened by popen() */+ }+ pid_t pid = found->pid;+ free(found);+ (void)fclose(f);+ return cbm_popen_git_wait(pid); /* the raw wait status, as pclose() */}FILE *cbm_fopen(const char *path, const char *mode) {diff --git a/src/foundation/compat_fs.h b/src/foundation/compat_fs.hindex a27bf66a2..1a572a478 100644--- a/src/foundation/compat_fs.h+++ b/src/foundation/compat_fs.h@@ -60,6 +60,13 @@ void cbm_closedir(cbm_dir_t *d);/* ── Portable popen/pclose ────────────────────────────────────── */FILE *cbm_popen(const char *cmd, const char *mode);++/* Read-mode cbm_popen for a `git ...` command line: the child environment+ * omits git's repository-local variables (foundation/git_env.h), so an+ * inherited GIT_DIR/GIT_WORK_TREE/... can never override `git -C <repo>`.+ * The caller's own environment is untouched. Close with cbm_pclose. */+FILE *cbm_popen_git(const char *cmd);+int cbm_pclose(FILE *f);/* ── File operations ──────────────────────────────────────────── */diff --git a/src/foundation/git_env.c b/src/foundation/git_env.cnew file mode 100644index 000000000..894b6fe6c--- /dev/null+++ b/src/foundation/git_env.c@@ -0,0 +1,162 @@+/*+ * git_env.c — child environment for cbm's git spawns. See git_env.h.+ */+#include "foundation/git_env.h"+#include "foundation/mem_core.h"++#include <stdlib.h>+#include <string.h>++#ifdef _WIN32+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#include <windows.h>+#else+extern char **environ;+#endif++const char *const cbm_git_repo_env_vars[CBM_GIT_REPO_ENV_VAR_COUNT] = {+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",+ "GIT_CONFIG",+ "GIT_CONFIG_PARAMETERS",+ "GIT_CONFIG_COUNT",+ "GIT_OBJECT_DIRECTORY",+ "GIT_DIR",+ "GIT_WORK_TREE",+ "GIT_IMPLICIT_WORK_TREE",+ "GIT_GRAFT_FILE",+ "GIT_INDEX_FILE",+ "GIT_NO_REPLACE_OBJECTS",+ "GIT_REPLACE_REF_BASE",+ "GIT_PREFIX",+ "GIT_SHALLOW_FILE",+ "GIT_COMMON_DIR",+};++static char git_env_fold(char c) {+#ifdef _WIN32+ return (c >= 'a' && c <= 'z') ? (char)(c - 'a' + 'A') : c;+#else+ return c;+#endif+}++/* Does the name part of `entry` (up to '=' or `name_len` chars) equal `var`? */+static bool git_env_name_equals(const char *entry, size_t name_len, const char *var) {+ size_t var_len = strlen(var);+ if (name_len != var_len) {+ return false;+ }+ for (size_t i = 0; i < var_len; i++) {+ if (git_env_fold(entry[i]) != var[i]) {+ return false;+ }+ }+ return true;+}++static bool git_env_name_is_repo_local(const char *name, size_t name_len) {+ for (size_t i = 0; i < CBM_GIT_REPO_ENV_VAR_COUNT; i++) {+ if (git_env_name_equals(name, name_len, cbm_git_repo_env_vars[i])) {+ return true;+ }+ }+ return false;+}++bool cbm_git_env_entry_is_repo_local(const char *entry) {+ if (!entry) {+ return false;+ }+ const char *eq = strchr(entry, '=');+ size_t name_len = eq ? (size_t)(eq - entry) : strlen(entry);+ return git_env_name_is_repo_local(entry, name_len);+}++#ifdef _WIN32++/* Wide entry name → is it repository-local? Names we match are ASCII, so any+ * non-ASCII code unit is an immediate mismatch. Windows keeps per-drive cwd+ * entries ("=C:=C:\\dir") whose name starts with '='; the search for the+ * separator starts at index 1 so they are kept untouched. */+static bool git_env_wide_entry_is_repo_local(const wchar_t *entry) {+ char name[64] = {0};+ size_t n = 0;+ for (size_t i = 0; entry[i] && (i == 0 || entry[i] != L'='); i++) {+ if (entry[i] > 0x7F || n + 1 >= sizeof(name)) {+ return false;+ }+ name[n++] = (char)entry[i];+ }+ return git_env_name_is_repo_local(name, n);+}++wchar_t *cbm_git_child_env_block(void) {+ wchar_t *current = GetEnvironmentStringsW();+ if (!current) {+ return NULL;+ }+ size_t kept = 0;+ for (const wchar_t *e = current; *e; e += wcslen(e) + 1) {+ if (!git_env_wide_entry_is_repo_local(e)) {+ kept += wcslen(e) + 1;+ }+ }+ /* +2: a block that keeps nothing still needs its double terminator. */+ wchar_t *block = (wchar_t *)cbm_alloc(CBM_MEM_CLASS_OTHER, (kept + 2) * sizeof(wchar_t));+ if (!block) {+ FreeEnvironmentStringsW(current);+ return NULL;+ }+ size_t pos = 0;+ for (const wchar_t *e = current; *e; e += wcslen(e) + 1) {+ if (!git_env_wide_entry_is_repo_local(e)) {+ size_t len = wcslen(e) + 1;+ memcpy(block + pos, e, len * sizeof(wchar_t));+ pos += len;+ }+ }+ block[pos] = L'\0';+ if (pos == 0) {+ block[1] = L'\0';+ }+ FreeEnvironmentStringsW(current);+ return block;+}++#else++char **cbm_git_child_envp(void) {+ size_t count = 0;+ size_t bytes = 0;+ for (char **e = environ; e && *e; e++) {+ if (!cbm_git_env_entry_is_repo_local(*e)) {+ count++;+ bytes += strlen(*e) + 1;+ }+ }+ size_t table = (count + 1) * sizeof(char *);+ char **envp = (char **)cbm_alloc(CBM_MEM_CLASS_OTHER, table + bytes);+ if (!envp) {+ return NULL;+ }+ char *strings = (char *)envp + table;+ size_t slot = 0;+ for (char **e = environ; e && *e && slot < count; e++) {+ if (!cbm_git_env_entry_is_repo_local(*e)) {+ size_t len = strlen(*e) + 1;+ memcpy(strings, *e, len);+ envp[slot++] = strings;+ strings += len;+ }+ }+ envp[slot] = NULL;+ return envp;+}++#endif++void cbm_git_child_env_free(void *env) {+ cbm_free(CBM_MEM_CLASS_OTHER, env);+}diff --git a/src/foundation/git_env.h b/src/foundation/git_env.hnew file mode 100644index 000000000..703a0e332--- /dev/null+++ b/src/foundation/git_env.h@@ -0,0 +1,47 @@+/*+ * git_env.h — the environment cbm hands to its OWN git child processes.+ *+ * Git exports repository-local variables into hooks and some editors export+ * them into their terminals (GIT_DIR, GIT_WORK_TREE, GIT_INDEX_FILE, ...). They+ * take precedence over `git -C <dir>`: a cbm started from such an environment+ * would otherwise resolve every indexed project against the CALLER's repository+ * (a non-git directory reported as is_git=true, history and branch data from+ * the wrong repo). Every git spawn therefore gets a child environment with+ * exactly the variables `git rev-parse --local-env-vars` prints removed. The+ * scrub is per spawn: cbm's own environment is never modified (unsetenv in the+ * parent would race every other thread reading the environment).+ */+#ifndef CBM_GIT_ENV_H+#define CBM_GIT_ENV_H++#include <stdbool.h>+#include <stddef.h>++#ifdef _WIN32+#include <wchar.h>+#endif++/* `git rev-parse --local-env-vars` (git 2.50) — the single source of truth. */+enum { CBM_GIT_REPO_ENV_VAR_COUNT = 15 };+extern const char *const cbm_git_repo_env_vars[CBM_GIT_REPO_ENV_VAR_COUNT];++/* True when a "NAME=value" environment entry names one of the variables above.+ * The name compare is case-insensitive on Windows (its environment is). */+bool cbm_git_env_entry_is_repo_local(const char *entry);++#ifdef _WIN32+/* A CREATE_UNICODE_ENVIRONMENT block: the current environment minus the+ * repository-local git variables. One allocation; release with cbm_git_child_env_free().+ * NULL on allocation/snapshot failure. */+wchar_t *cbm_git_child_env_block(void);+#else+/* A NULL-terminated envp: the current environment minus the repository-local+ * git variables. Pointers and strings live in ONE allocation; release with+ * cbm_git_child_env_free(). NULL on allocation failure. */+char **cbm_git_child_envp(void);+#endif++/* Release a block from cbm_git_child_env_block / cbm_git_child_envp. NULL is a no-op. */+void cbm_git_child_env_free(void *env);++#endif /* CBM_GIT_ENV_H */diff --git a/src/foundation/subprocess.c b/src/foundation/subprocess.cindex 83f788937..2e08da328 100644--- a/src/foundation/subprocess.c+++ b/src/foundation/subprocess.c@@ -7,6 +7,7 @@#include "compat.h" /* cbm_nanosleep */#include "compat_fs.h"+#include "git_env.h" /* strip_git_repo_env: scrubbed child environment for git */#include "log.h"#include "platform.h" /* cbm_now_ms */#include "sanitized.h" /* CBM_SANITIZED — spawn-retry budget */@@ -27,8 +28,8 @@#include <signal.h>#ifdef __APPLE__#include <spawn.h>-extern char **environ;#endif+extern char **environ;#include <sys/stat.h>#include <sys/wait.h>#include <unistd.h>@@ -413,6 +414,10 @@ struct cbm_subprocess {int cancel_grace_ms;size_t memory_limit_bytes;bool delete_log_on_exit;+ bool strip_git_repo_env;+#ifndef _WIN32+ char **envp; /* NULL => inherit environ; else the scrubbed git child env */+#endiflong tail_pos;uint64_t last_activity_ms;@@ -463,6 +468,9 @@ static void cbm_subprocess_free_config(cbm_subprocess_t *process) {free(process->bin);free(process->windows_cmd_payload);free(process->log_file);+#ifndef _WIN32+ cbm_git_child_env_free(process->envp);+#endiffree(process);}@@ -531,6 +539,18 @@ static cbm_subprocess_t *cbm_subprocess_copy_opts(const cbm_proc_opts_t *opts) {}process->memory_limit_bytes = opts->memory_limit_bytes;process->delete_log_on_exit = opts->delete_log_on_exit;+ process->strip_git_repo_env = opts->strip_git_repo_env;+#ifndef _WIN32+ /* Built before the spawn: the fork child may only assign it (malloc is+ * not async-signal-safe there). Fail closed rather than inherit GIT_DIR. */+ if (opts->strip_git_repo_env) {+ process->envp = cbm_git_child_envp();+ if (!process->envp) {+ cbm_subprocess_free_config(process);+ return NULL;+ }+ }+#endifatomic_init(&process->lifecycle, CBM_SUBPROCESS_ACTIVE);cbm_subprocess_result_init(&process->result);return process;@@ -746,8 +766,15 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {ZeroMemory(&child, sizeof(child));DWORD flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP |CREATE_NO_WINDOW;- BOOL created = CreateProcessW(wbin, wcmdline, NULL, NULL, TRUE, flags, NULL, NULL,+ /* Fail closed: a git child must never inherit a caller's GIT_DIR. */+ wchar_t *env = process->strip_git_repo_env ? cbm_git_child_env_block() : NULL;+ if (env) {+ flags |= CREATE_UNICODE_ENVIRONMENT;+ }+ BOOL created = (!process->strip_git_repo_env || env) &&+ CreateProcessW(wbin, wcmdline, NULL, NULL, TRUE, flags, (LPVOID)env, NULL,&startup.StartupInfo, &child);+ cbm_git_child_env_free(env); /* CreateProcessW copied the block into the child */cbm_win_close_spawn_handles(nul, log, attrs, attrs_init);free(wbin);free(wcmdline);@@ -1066,6 +1093,9 @@ static void cbm_posix_child_exec(cbm_subprocess_t *process, int input, int outpufor (int fd = STDERR_FILENO + 1; fd < max_fd; fd++) {(void)close(fd);}+ if (process->envp) {+ environ = process->envp; /* execvp passes environ to the new image */+ }/* A fixed literal tool name (for example "git" or "curl") uses the* caller's normal PATH without introducing a shell. An explicit path* still has execvp's exact-path semantics because it contains '/'. */@@ -1143,8 +1173,9 @@ static int cbm_posix_spawn_apple(cbm_subprocess_t *process, int input, int outpuposix_spawn_file_actions_adddup2(&actions, output, STDOUT_FILENO) == 0 &&posix_spawn_file_actions_adddup2(&actions, output, STDERR_FILENO) == 0;pid_t pid = -1;- int rc =- configured ? posix_spawnp(&pid, process->bin, &actions, &attr, process->argv, environ) : -1;+ int rc = configured ? posix_spawnp(&pid, process->bin, &actions, &attr, process->argv,+ process->envp ? process->envp : environ)+ : -1;(void)posix_spawn_file_actions_destroy(&actions);(void)posix_spawnattr_destroy(&attr);if (configured && rc == 0 && pid > 0) {diff --git a/src/foundation/subprocess.h b/src/foundation/subprocess.hindex 54940de11..333509fb6 100644--- a/src/foundation/subprocess.h+++ b/src/foundation/subprocess.h@@ -74,6 +74,9 @@ typedef struct {size_t memory_limit_bytes; /* Windows-only hard commit limit for the entire Job Object;* 0 => no OS-enforced memory limit */bool delete_log_on_exit; /* unlink log_file after reaping */+ bool strip_git_repo_env; /* child env omits git's repository-local variables+ * (foundation/git_env.h) — set for every git spawn so+ * an inherited GIT_DIR never overrides `git -C` */} cbm_proc_opts_t;#define CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS 1000diff --git a/src/git/git_context.c b/src/git/git_context.cindex f739c46e6..728713706 100644--- a/src/git/git_context.c+++ b/src/git/git_context.c@@ -65,7 +65,7 @@ static int git_capture(const char *repo_path, const char *git_args, char **out)return CBM_NOT_FOUND;}- FILE *fp = cbm_popen(cmd, "r");+ FILE *fp = cbm_popen_git(cmd);if (!fp) {return CBM_NOT_FOUND;}diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex 75ff8e396..0e1d4db32 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -14398,7 +14398,7 @@ static bool compile_path_filter(const char *filter, cbm_regex_t *re) {static mcp_scan_cause_t mcp_run_shell_command_cancellable_bounded(cbm_mcp_server_t *srv, const char *command, char output_path[CBM_SZ_2K], size_t output_limit,uint64_t deadline_ms, bool deadline_enabled, bool deadline_latched, bool exit_one_is_no_match,- cbm_proc_result_t *result_out);+ bool git_child, cbm_proc_result_t *result_out);static char *search_code_timeout_result(void) {static const char message[] = "search_code scan exceeded its execution deadline";@@ -14739,7 +14739,8 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {srv->search_scan_command_override ? srv->search_scan_command_override : cmd;mcp_scan_cause_t scan_cause = mcp_run_shell_command_cancellable_bounded(srv, scan_command, output_path, scan_output_limit, scan_deadline_ms, true,- scan_deadline_latched, /*exit_one_is_no_match=*/false, &scan_result);+ scan_deadline_latched, /*exit_one_is_no_match=*/false, /*git_child=*/false,+ &scan_result);/* Both POSIX commands wrap grep and map its no-match status to 0, so any* non-zero exit (a failed find/sort, an unreadable operand, a broken* grep) is an incomplete scan and fails closed. */@@ -15099,7 +15100,7 @@ static mcp_scan_cause_t mcp_scan_pre_spawn_cause(cbm_mcp_server_t *srv, const chstatic mcp_scan_cause_t mcp_run_shell_command_cancellable_bounded(cbm_mcp_server_t *srv, const char *command, char output_path[CBM_SZ_2K], size_t output_limit,uint64_t deadline_ms, bool deadline_enabled, bool deadline_latched, bool exit_one_is_no_match,- cbm_proc_result_t *result_out) {+ bool git_child, cbm_proc_result_t *result_out) {if (!srv || !command || !output_path || !result_out) {return MCP_SCAN_COMMAND_FAILURE;}@@ -15157,6 +15158,7 @@ static mcp_scan_cause_t mcp_run_shell_command_cancellable_bounded(.quiet_timeout_ms = 0,.cancel_grace_ms = CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS,.delete_log_on_exit = false,+ .strip_git_repo_env = git_child,};pre_spawn_cause =mcp_scan_pre_spawn_cause(srv, output_path, output_limit, deadline_ms, deadline_enabled,@@ -15234,11 +15236,14 @@ static mcp_scan_cause_t mcp_run_shell_command_cancellable_bounded(: MCP_SCAN_CONTAINED_COMMAND_FAILURE;}+/* Every caller is a detect_changes git command: the child environment drops+ * git's repository-local variables so an inherited GIT_DIR cannot redirect+ * `git -C <root>` (#2003). */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) {mcp_scan_cause_t cause = mcp_run_shell_command_cancellable_bounded(- srv, command, output_path, 0, 0, false, false, false, result_out);+ srv, command, output_path, 0, 0, false, false, false, /*git_child=*/true, result_out);/* Legacy callers inspect result_out for cancellation/exit status. Preserve* their original contract: any contained terminal tree is transport* success; only spawn/rejection or failed supervision is a wrapper error. */diff --git a/src/pipeline/artifact.c b/src/pipeline/artifact.cindex 2dd368c28..378de49f2 100644--- a/src/pipeline/artifact.c+++ b/src/pipeline/artifact.c@@ -255,7 +255,7 @@ static bool git_head_hash(const char *repo_path, char *buf, size_t bufsz) {git_context.c) */return false;}- FILE *fp = cbm_popen(cmd, "r");+ FILE *fp = cbm_popen_git(cmd);if (!fp) {buf[0] = '\0';return false;@@ -397,7 +397,7 @@ static bool git_run_ok(const char *repo_path, const char *args) {if (!build_git_cmd(cmd, sizeof(cmd), repo_path, args)) {return false;}- FILE *fp = cbm_popen(cmd, "r");+ FILE *fp = cbm_popen_git(cmd);if (!fp) {return false;}@@ -416,7 +416,7 @@ static int git_capture_full(const char *repo_path, const char *args, char **out,if (!build_git_cmd(cmd, sizeof(cmd), repo_path, args)) {return CBM_NOT_FOUND;}- FILE *fp = cbm_popen(cmd, "r");+ FILE *fp = cbm_popen_git(cmd);if (!fp) {return CBM_NOT_FOUND;}@@ -813,7 +813,7 @@ static void ensure_gitattributes(const char *repo_path) {if (n < 0 || (size_t)n >= sizeof(cmd)) {return; /* truncated command → skip (parity with git_context.c) */}- FILE *p = cbm_popen(cmd, "r");+ FILE *p = cbm_popen_git(cmd);if (p) {(void)cbm_pclose(p);}diff --git a/src/pipeline/pass_githistory.c b/src/pipeline/pass_githistory.cindex 554acea2f..97d057442 100644--- a/src/pipeline/pass_githistory.c+++ b/src/pipeline/pass_githistory.c@@ -130,7 +130,7 @@ static int parse_git_log(const char *repo_path, commit_t **out, int *out_count)"--since=\"1 year ago\" --max-count=10000 2>%s",repo_path, null_dev);- FILE *fp = cbm_popen(cmd, "r");+ FILE *fp = cbm_popen_git(cmd);if (!fp) {return CBM_NOT_FOUND;}diff --git a/src/watcher/watcher.c b/src/watcher/watcher.cindex 95dfc1725..78ea21fe3 100644--- a/src/watcher/watcher.c+++ b/src/watcher/watcher.c@@ -393,6 +393,7 @@ static watcher_git_status_t watcher_git_run(cbm_watcher_t *w, project_state_t *s.quiet_timeout_ms = 0,.cancel_grace_ms = CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS,.delete_log_on_exit = false,+ .strip_git_repo_env = true, /* #2003: an inherited GIT_DIR must not redirect -C */};cbm_subprocess_t *process = NULL;if (cbm_subprocess_spawn(&options, &process) != 0) {diff --git a/tests/test_git_context.c b/tests/test_git_context.cindex a384651a5..aede35533 100644--- a/tests/test_git_context.c+++ b/tests/test_git_context.c@@ -26,6 +26,11 @@#include "test_framework.h"#include "test_helpers.h"#include "git/git_context.h"+#include "foundation/compat.h"+#include "foundation/git_env.h"+#include "pipeline/pipeline_internal.h"++#include <stdlib.h>#include <stdio.h>#include <string.h>@@ -61,6 +66,94 @@ static int make_git_repo(const char *dir) {}#endif /* _WIN32 */+#ifndef _WIN32+/* ── Inherited repository-local git environment (#2003) ────────────+ * A cbm started from a git hook (or an editor that exports GIT_DIR) inherits+ * GIT_DIR/GIT_WORK_TREE/GIT_INDEX_FILE/..., which override `git -C <dir>`.+ * Production must clear them for its own git children (per spawn). These+ * tests set the hook set explicitly (the runner may clear it at startup) and+ * restore the caller's values before asserting, so a failure never leaks the+ * decoy environment into later tests. */++typedef struct {+ char *saved[CBM_GIT_REPO_ENV_VAR_COUNT];+ bool present[CBM_GIT_REPO_ENV_VAR_COUNT];+} git_env_snapshot_t;++static void git_env_hook_enter(git_env_snapshot_t *snap, const char *decoy) {+ for (int i = 0; i < CBM_GIT_REPO_ENV_VAR_COUNT; i++) {+ const char *v = getenv(cbm_git_repo_env_vars[i]);+ snap->present[i] = v != NULL;+ snap->saved[i] = v ? strdup(v) : NULL;+ }+ char buf[1024];+ snprintf(buf, sizeof(buf), "%s/.git", decoy);+ cbm_setenv("GIT_DIR", buf, 1);+ cbm_setenv("GIT_COMMON_DIR", buf, 1);+ cbm_setenv("GIT_WORK_TREE", decoy, 1);+ snprintf(buf, sizeof(buf), "%s/.git/index", decoy);+ cbm_setenv("GIT_INDEX_FILE", buf, 1);+ snprintf(buf, sizeof(buf), "%s/.git/objects", decoy);+ cbm_setenv("GIT_OBJECT_DIRECTORY", buf, 1);+ cbm_setenv("GIT_PREFIX", "", 1);+}++static void git_env_hook_leave(git_env_snapshot_t *snap) {+ for (int i = 0; i < CBM_GIT_REPO_ENV_VAR_COUNT; i++) {+ if (snap->present[i]) {+ cbm_setenv(cbm_git_repo_env_vars[i], snap->saved[i], 1);+ } else {+ cbm_unsetenv(cbm_git_repo_env_vars[i]);+ }+ free(snap->saved[i]);+ snap->saved[i] = NULL;+ }+}++/* First output line of `git -C dir <args>` (run with the test's clean env). */+static void git_read_line(const char *dir, const char *args, char *out, size_t out_sz) {+ char cmd[1024];+ out[0] = '\0';+ snprintf(cmd, sizeof(cmd), "git -C \"%s\" %s 2>/dev/null", dir, args);+ FILE *fp = popen(cmd, "r");+ if (!fp)+ return;+ if (fgets(out, (int)out_sz, fp)) {+ out[strcspn(out, "\r\n")] = '\0';+ }+ pclose(fp);+}++/* root/decoy: a repo on branch decoy-branch with coupled a.go+b.go commits;+ * root/fixture: a repo on branch fixture-branch; root/plain: not a repo. */+static int make_env_isolation_tree(const char *root) {+ char decoy[512], fixture[512], plain[512], path[600];+ snprintf(decoy, sizeof(decoy), "%s/decoy", root);+ snprintf(fixture, sizeof(fixture), "%s/fixture", root);+ snprintf(plain, sizeof(plain), "%s/plain", root);+ if (make_git_repo(decoy) != 0 || make_git_repo(fixture) != 0)+ return -1;+ if (git_run(decoy, "checkout -q -b decoy-branch") != 0)+ return -1;+ if (git_run(fixture, "checkout -q -b fixture-branch") != 0)+ return -1;+ for (int i = 0; i < 3; i++) {+ char content[32];+ snprintf(content, sizeof(content), "package a // %d\n", i);+ snprintf(path, sizeof(path), "%s/a.go", decoy);+ th_write_file(path, content);+ snprintf(path, sizeof(path), "%s/b.go", decoy);+ th_write_file(path, content);+ if (git_run(decoy, "add a.go b.go") != 0)+ return -1;+ if (git_run(decoy, "commit -q -m decoy") != 0)+ return -1;+ }+ return th_mkdir_p(plain);+}++#endif /* _WIN32 */+/* ── canonical_root: normal repo indexed from its root ──────────── */TEST(canonical_root_repo_root) {@@ -232,10 +325,106 @@ TEST(canonical_root_linked_worktree) {#endif /* _WIN32 */}+TEST(git_context_ignores_inherited_repo_env) {+#ifdef _WIN32+ SKIP_PLATFORM("git-based env-isolation test not supported on Windows CI");+#else+ char root[256];+ char *raw = th_mktempdir("cbm_gitenv");+ if (!raw)+ FAIL("th_mktempdir returned NULL");+ snprintf(root, sizeof(root), "%s", raw);+ if (make_env_isolation_tree(root) != 0) {+ th_rmtree(root);+ SKIP_PLATFORM("git not available to init a repo");+ }+ char decoy[512], fixture[512], plain[512];+ snprintf(decoy, sizeof(decoy), "%s/decoy", root);+ snprintf(fixture, sizeof(fixture), "%s/fixture", root);+ snprintf(plain, sizeof(plain), "%s/plain", root);++ char decoy_head[128], decoy_branch[128], fixture_head[128];+ git_read_line(decoy, "rev-parse HEAD", decoy_head, sizeof(decoy_head));+ git_read_line(decoy, "rev-parse --abbrev-ref HEAD", decoy_branch, sizeof(decoy_branch));+ git_read_line(fixture, "rev-parse HEAD", fixture_head, sizeof(fixture_head));++ git_env_snapshot_t snap;+ git_env_hook_enter(&snap, decoy);+ cbm_git_context_t plain_ctx = {0};+ int plain_rc = cbm_git_context_resolve(plain, &plain_ctx);+ cbm_git_context_t fix_ctx = {0};+ int fix_rc = cbm_git_context_resolve(fixture, &fix_ctx);+ git_env_hook_leave(&snap);++ bool plain_is_git = plain_ctx.is_git;+ char fix_head[128], fix_branch[128];+ snprintf(fix_head, sizeof(fix_head), "%s", fix_ctx.head_sha ? fix_ctx.head_sha : "");+ snprintf(fix_branch, sizeof(fix_branch), "%s", fix_ctx.branch ? fix_ctx.branch : "");+ bool fix_is_git = fix_ctx.is_git;+ cbm_git_context_free(&plain_ctx);+ cbm_git_context_free(&fix_ctx);++ char decoy_head_after[128], decoy_branch_after[128];+ git_read_line(decoy, "rev-parse HEAD", decoy_head_after, sizeof(decoy_head_after));+ git_read_line(decoy, "rev-parse --abbrev-ref HEAD", decoy_branch_after,+ sizeof(decoy_branch_after));+ th_rmtree(root);++ ASSERT_EQ(plain_rc, 0);+ ASSERT_FALSE(plain_is_git); /* a plain dir is not the decoy's repo */+ ASSERT_EQ(fix_rc, 0);+ ASSERT_TRUE(fix_is_git);+ ASSERT_STR_EQ(fix_head, fixture_head); /* the fixture's HEAD, not the decoy's */+ ASSERT_STR_EQ(fix_branch, "fixture-branch");+ ASSERT_STR_EQ(decoy_head_after, decoy_head); /* the decoy is untouched */+ ASSERT_STR_EQ(decoy_branch_after, decoy_branch);+ PASS();+#endif /* _WIN32 */+}++TEST(githistory_ignores_inherited_repo_env) {+#ifdef _WIN32+ SKIP_PLATFORM("git-based env-isolation test not supported on Windows CI");+#else+ char root[256];+ char *raw = th_mktempdir("cbm_gitenv_hist");+ if (!raw)+ FAIL("th_mktempdir returned NULL");+ snprintf(root, sizeof(root), "%s", raw);+ if (make_env_isolation_tree(root) != 0) {+ th_rmtree(root);+ SKIP_PLATFORM("git not available to init a repo");+ }+ char decoy[512], plain[512];+ snprintf(decoy, sizeof(decoy), "%s/decoy", root);+ snprintf(plain, sizeof(plain), "%s/plain", root);++ git_env_snapshot_t snap;+ git_env_hook_enter(&snap, decoy);+ cbm_githistory_result_t result = {0};+ (void)cbm_pipeline_githistory_compute(plain, &result);+ git_env_hook_leave(&snap);++ int commits = result.commit_count;+ int couplings = result.count;+ free(result.couplings);+ free(result.file_temporal);+ th_rmtree(root);++ /* A non-git directory has no history: the decoy's 3 coupled commits+ * must not be attributed to it. */+ ASSERT_EQ(commits, 0);+ ASSERT_EQ(couplings, 0);+ PASS();+#endif /* _WIN32 */+}+/* ── Suite ──────────────────────────────────────────────────────── */SUITE(git_context) {RUN_TEST(canonical_root_repo_root);RUN_TEST(canonical_root_subdir);RUN_TEST(canonical_root_linked_worktree);+ RUN_TEST(git_context_ignores_inherited_repo_env);+ RUN_TEST(githistory_ignores_inherited_repo_env);}diff --git a/tests/test_subprocess.c b/tests/test_subprocess.cindex 308d6b584..fb9788f76 100644--- a/tests/test_subprocess.c+++ b/tests/test_subprocess.c@@ -12,16 +12,20 @@#include "../src/foundation/subprocess.h"#include "../src/foundation/compat.h"#include "../src/foundation/platform.h"+#include "../src/foundation/compat_fs.h"+#include "../src/foundation/git_env.h"#include <errno.h>#include <limits.h>#include <stdio.h>+#include <stdlib.h>#include <string.h>#ifndef _WIN32#include <fcntl.h>#include <signal.h>#include <sys/time.h>+#include <sys/wait.h>#include <unistd.h>#else#include <windows.h>@@ -1256,6 +1260,114 @@ TEST(win_cmd_payload_rejects_short_relative_and_non_cmd_paths) {PASS();}+/* ── Git child environment (#2003) ────────────────────────────────────────────+ * strip_git_repo_env / cbm_popen_git drop every variable of+ * `git rev-parse --local-env-vars` from the CHILD only: the parent keeps its+ * environment, other variables pass through, and without the flag a child+ * still inherits everything. The test sets the variables itself (a runner may+ * clear them at startup) and restores them before asserting. */+#ifndef _WIN32+typedef struct {+ char *saved[CBM_GIT_REPO_ENV_VAR_COUNT];+ bool present[CBM_GIT_REPO_ENV_VAR_COUNT];+} gitenv_snapshot_t;++static void gitenv_enter(gitenv_snapshot_t *snap) {+ for (int i = 0; i < CBM_GIT_REPO_ENV_VAR_COUNT; i++) {+ const char *v = getenv(cbm_git_repo_env_vars[i]);+ snap->present[i] = v != NULL;+ snap->saved[i] = v ? strdup(v) : NULL;+ setenv(cbm_git_repo_env_vars[i], "/cbm-decoy-repo", 1);+ }+ setenv("CBM_GITENV_KEEP", "kept", 1);+}++static void gitenv_leave(gitenv_snapshot_t *snap) {+ for (int i = 0; i < CBM_GIT_REPO_ENV_VAR_COUNT; i++) {+ if (snap->present[i]) {+ setenv(cbm_git_repo_env_vars[i], snap->saved[i], 1);+ } else {+ unsetenv(cbm_git_repo_env_vars[i]);+ }+ free(snap->saved[i]);+ }+ unsetenv("CBM_GITENV_KEEP");+}++/* exit 0: no git repo-local var is set and CBM_GITENV_KEEP=kept; exit 3: a git+ * var leaked; exit 4: the unrelated variable was lost. */+static void gitenv_probe_script(char *buf, size_t cap) {+ size_t n = (size_t)snprintf(buf, cap, "[ \"$CBM_GITENV_KEEP\" = kept ] || exit 4;");+ for (int i = 0; i < CBM_GIT_REPO_ENV_VAR_COUNT && n < cap; i++) {+ n += (size_t)snprintf(buf + n, cap - n, " [ -z \"${%s+x}\" ] || exit 3;",+ cbm_git_repo_env_vars[i]);+ }+ if (n < cap) {+ (void)snprintf(buf + n, cap - n, " exit 0");+ }+}++static int gitenv_spawn_probe(bool strip) {+ char script[2048];+ gitenv_probe_script(script, sizeof(script));+ const char *argv[] = {"/bin/sh", "-c", script, NULL};+ cbm_proc_opts_t opts = {.bin = "/bin/sh", .argv = argv, .strip_git_repo_env = strip};+ cbm_proc_result_t r;+ if (cbm_subprocess_run(&opts, &r) != 0) {+ return -1;+ }+ return r.exit_code;+}+#endif++TEST(subprocess_strip_git_repo_env_is_per_child) {+#ifdef _WIN32+ SKIP_PLATFORM("POSIX /bin/sh spawn");+#else+ gitenv_snapshot_t snap;+ gitenv_enter(&snap);+ int stripped = gitenv_spawn_probe(true);+ int inherited = gitenv_spawn_probe(false);+ const char *parent_git_dir = getenv("GIT_DIR");+ bool parent_kept = parent_git_dir && strcmp(parent_git_dir, "/cbm-decoy-repo") == 0;+ gitenv_leave(&snap);+ ASSERT_EQ(stripped, 0); /* git vars gone, CBM_GITENV_KEEP passed through */+ ASSERT_EQ(inherited, 3); /* without the flag the child inherits as before */+ ASSERT_TRUE(parent_kept); /* the parent environment is never modified */+ PASS();+#endif+}++TEST(popen_git_strips_repo_env_and_reports_exit_status) {+#ifdef _WIN32+ SKIP_PLATFORM("POSIX /bin/sh spawn");+#else+ char script[2048];+ gitenv_probe_script(script, sizeof(script));+ char cmd[2200];+ snprintf(cmd, sizeof(cmd), "echo probe; %s", script);+ gitenv_snapshot_t snap;+ gitenv_enter(&snap);+ FILE *fp = cbm_popen_git(cmd);+ char line[64] = {0};+ bool got_line = fp && fgets(line, sizeof(line), fp) != NULL;+ int status = fp ? cbm_pclose(fp) : -1;+ FILE *fail = cbm_popen_git("exit 7");+ int fail_status = fail ? cbm_pclose(fail) : -1;+ const char *parent_git_dir = getenv("GIT_DIR");+ bool parent_kept = parent_git_dir && strcmp(parent_git_dir, "/cbm-decoy-repo") == 0;+ gitenv_leave(&snap);+ ASSERT_TRUE(got_line);+ ASSERT_STR_EQ(line, "probe\n");+ ASSERT_TRUE(status >= 0 && WIFEXITED(status));+ ASSERT_EQ(WEXITSTATUS(status), 0);+ ASSERT_TRUE(fail_status >= 0 && WIFEXITED(fail_status));+ ASSERT_EQ(WEXITSTATUS(fail_status), 7); /* pclose() semantics: raw wait status */+ ASSERT_TRUE(parent_kept);+ PASS();+#endif+}+SUITE(subprocess) {RUN_TEST(subprocess_classify_clean);RUN_TEST(subprocess_classify_exit_nonzero);@@ -1285,6 +1397,8 @@ SUITE(subprocess) {RUN_TEST(subprocess_final_log_drain_error_is_terminal_and_preserves_classification);RUN_TEST(subprocess_posix_child_closes_unrelated_descriptors);RUN_TEST(subprocess_root_exit_drains_surviving_descendant);+ RUN_TEST(subprocess_strip_git_repo_env_is_per_child);+ RUN_TEST(popen_git_strips_repo_env_and_reports_exit_status);RUN_TEST(win_cmdline_index_worker_json);RUN_TEST(win_cmdline_roundtrip_battery);RUN_TEST(win_cmdline_overflow_rejected);