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
Full Windows portability: proper implementations, not stubs
Martin Vogel85fc74fc31eb
diff --git a/Makefile.cbm b/Makefile.cbmindex 8352e09b2..fa7f25da4 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -75,9 +75,13 @@ CFLAGS_TSAN = $(CFLAGS_COMMON) -g -O1 \CXXFLAGS_TSAN = $(CXXFLAGS_COMMON) -g -O1 \-fsanitize=thread -fno-omit-frame-pointer-LDFLAGS = -lm -lstdc++ -lpthread -lz $(LIBGIT2_LIBS)-LDFLAGS_TEST = -lm -lstdc++ -lpthread -lz -fsanitize=address,undefined $(LIBGIT2_LIBS)-LDFLAGS_TSAN = -lm -lstdc++ -lpthread -lz -fsanitize=thread $(LIBGIT2_LIBS)+# Windows needs ws2_32 (Winsock) and psapi (GetProcessMemoryInfo).+# Override via: make WIN32_LIBS="-lws2_32 -lpsapi" for cross-compilation.+WIN32_LIBS ?=++LDFLAGS = -lm -lstdc++ -lpthread -lz $(LIBGIT2_LIBS) $(WIN32_LIBS)+LDFLAGS_TEST = -lm -lstdc++ -lpthread -lz -fsanitize=address,undefined $(LIBGIT2_LIBS) $(WIN32_LIBS)+LDFLAGS_TSAN = -lm -lstdc++ -lpthread -lz -fsanitize=thread $(LIBGIT2_LIBS) $(WIN32_LIBS)# ── Source files ─────────────────────────────────────────────────diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.cindex 078a32cbd..6162c7a8a 100644--- a/internal/cbm/cbm.c+++ b/internal/cbm/cbm.c@@ -28,7 +28,7 @@ static _Atomic uint64_t total_files = 0;static uint64_t now_ns(void) {struct timespec ts;// NOLINTNEXTLINE(misc-include-cleaner) — clock_gettime provided by standard header- clock_gettime(CLOCK_MONOTONIC, &ts);+ cbm_clock_gettime(CLOCK_MONOTONIC, &ts);return ((uint64_t)ts.tv_sec * NSEC_PER_SEC) + (uint64_t)ts.tv_nsec;}diff --git a/src/discover/discover.c b/src/discover/discover.cindex a8d2f0a9c..a3aa007bc 100644--- a/src/discover/discover.c+++ b/src/discover/discover.c@@ -251,14 +251,20 @@ static void walk_dir(const char *dir_path, const char *rel_prefix, const cbm_dis}struct stat st;+#ifdef _WIN32+ if (stat(abs_path, &st) != 0) {+ continue;+ }+ /* Windows: no symlink detection via stat */+#elseif (lstat(abs_path, &st) != 0) {continue;}-/* Skip symlinks */if (S_ISLNK(st.st_mode)) {continue;}+#endifif (S_ISDIR(st.st_mode)) {/* Check hardcoded directory skip */diff --git a/src/foundation/compat.c b/src/foundation/compat.cindex cfedb4fe9..dd94b9e81 100644--- a/src/foundation/compat.c+++ b/src/foundation/compat.c@@ -29,6 +29,35 @@ char *cbm_strndup(const char *s, size_t n) {}#endif+/* ── strcasestr (Windows lacks it) ────────────────────────────── */++#ifdef _WIN32+char *cbm_strcasestr(const char *haystack, const char *needle) {+ if (!needle[0])+ return (char *)haystack;+ size_t nlen = strlen(needle);+ for (; *haystack; haystack++) {+ if (_strnicmp(haystack, needle, nlen) == 0)+ return (char *)haystack;+ }+ return NULL;+}+#endif++/* ── clock_gettime (Windows lacks it) ─────────────────────────── */++#ifdef _WIN32+int cbm_clock_gettime(int clk_id, struct timespec *tp) {+ (void)clk_id;+ LARGE_INTEGER freq, count;+ QueryPerformanceFrequency(&freq);+ QueryPerformanceCounter(&count);+ tp->tv_sec = (time_t)(count.QuadPart / freq.QuadPart);+ tp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * 1000000000LL / freq.QuadPart);+ return 0;+}+#endif+/* ── getline (Windows lacks it) ───────────────────────────────── */#ifdef _WIN32diff --git a/src/foundation/compat.h b/src/foundation/compat.hindex 3363cd1c4..626751697 100644--- a/src/foundation/compat.h+++ b/src/foundation/compat.h@@ -53,6 +53,41 @@ ssize_t cbm_getline(char **lineptr, size_t *n, FILE *stream);#define cbm_fileno fileno#endif+/* ── strcasestr (Windows lacks it) ────────────────────────────── */+#ifdef _WIN32+/* Implemented in compat.c */+char *cbm_strcasestr(const char *haystack, const char *needle);+#else+#define cbm_strcasestr strcasestr+#endif++/* ── mkdir portability ───────────────────────────────────────── */+#ifdef _WIN32+#include <direct.h>+#define cbm_mkdir(path) _mkdir(path)+#else+#include <sys/stat.h>+#define cbm_mkdir(path) mkdir(path, 0755)+#endif++/* ── clock_gettime / nanosleep (Windows lacks them) ──────────── */+#include <time.h>+#ifdef _WIN32+#ifndef CLOCK_MONOTONIC+#define CLOCK_MONOTONIC 1+#endif+/* Implemented in compat.c */+int cbm_clock_gettime(int clk_id, struct timespec *tp);+static inline int cbm_nanosleep(const struct timespec *req, struct timespec *rem) {+ (void)rem;+ Sleep((DWORD)(req->tv_sec * 1000 + req->tv_nsec / 1000000));+ return 0;+}+#else+#define cbm_clock_gettime clock_gettime+#define cbm_nanosleep nanosleep+#endif+/* ── Signal handling ──────────────────────────────────────────── *//* Windows doesn't have sigaction; provide macro to select signal API. */#ifdef _WIN32diff --git a/src/foundation/platform.c b/src/foundation/platform.cindex 615c8944b..2c33e4fe9 100644--- a/src/foundation/platform.c+++ b/src/foundation/platform.c@@ -4,6 +4,7 @@* macOS, Linux, and Windows. Platform-specific code behind #ifdef guards.*/#include "platform.h"+#include "compat.h"#include <stdint.h> // uint64_t, int64_t@@ -166,7 +167,7 @@ uint64_t cbm_now_ns(void) {#elseuint64_t cbm_now_ns(void) {struct timespec ts;- clock_gettime(CLOCK_MONOTONIC, &ts);+ cbm_clock_gettime(CLOCK_MONOTONIC, &ts);return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;}#endifdiff --git a/src/foundation/system_info.c b/src/foundation/system_info.cindex 4bbd88d8f..347855d00 100644--- a/src/foundation/system_info.c+++ b/src/foundation/system_info.c@@ -18,7 +18,7 @@#include <windows.h>#elif defined(__APPLE__)#include <sys/sysctl.h>-#else /* Linux */+#elif !defined(_WIN32) /* Linux */#include <unistd.h>#include <sys/sysinfo.h>#endif@@ -68,7 +68,7 @@ static cbm_system_info_t detect_system_macos(void) {return info;}-#else /* Linux */+#elif !defined(_WIN32) /* Linux */static cbm_system_info_t detect_system_linux(void) {cbm_system_info_t info;diff --git a/src/foundation/vmem.c b/src/foundation/vmem.cnew file mode 100644index 000000000..e71f01ed5--- /dev/null+++ b/src/foundation/vmem.c@@ -0,0 +1,205 @@+/*+ * vmem.c — Budget-tracked virtual memory allocator.+ *+ * Allocates via mmap (POSIX) or VirtualAlloc (Windows) to bypass+ * ptmalloc2's per-thread arena fragmentation. All allocations are+ * page-aligned, zeroed by the OS, and tracked against a configurable+ * budget (fraction of physical RAM).+ *+ * Pressure events are logged with hysteresis to avoid log storms+ * near the budget boundary.+ */+#include "vmem.h"+#include "platform.h"+#include "log.h"++#include <stdatomic.h>+#include <stdio.h> /* snprintf */+#include <string.h> /* memset */++#ifdef _WIN32+ #ifndef WIN32_LEAN_AND_MEAN+ #define WIN32_LEAN_AND_MEAN+ #endif+ #include <windows.h>+#else+ #include <sys/mman.h>+ #include <unistd.h> /* sysconf, _SC_PAGESIZE */+#endif++/* ── Static state (initialized once) ──────────────────────────── */++static atomic_size_t g_allocated = 0; /* current total allocated */+static atomic_size_t g_peak = 0; /* high-water mark */+static size_t g_budget = 0; /* budget in bytes */+static atomic_int g_was_over = 0; /* hysteresis: was over budget? */+static atomic_int g_initialized = 0; /* init guard */++/* ── Page size ─────────────────────────────────────────────────── */++static size_t page_size(void) {+#ifdef _WIN32+ SYSTEM_INFO si;+ GetSystemInfo(&si);+ return (size_t)si.dwPageSize;+#else+ long ps = sysconf(_SC_PAGESIZE);+ return ps > 0 ? (size_t)ps : 4096;+#endif+}++/* Round up to page boundary. */+static size_t round_to_page(size_t size) {+ size_t ps = page_size();+ return (size + ps - 1) & ~(ps - 1);+}++/* ── Pressure logging ──────────────────────────────────────────── */++#define MB_DIVISOR ((size_t)(1024 * 1024))++static void check_pressure(size_t allocated) {+ if (g_budget == 0) {+ return;+ }++ bool over = allocated > g_budget;+ int was = atomic_load(&g_was_over);++ if (over && !was) {+ /* Transition: under → over */+ atomic_store(&g_was_over, 1);+ char alloc_mb[32];+ char budget_mb[32];+ char pct_str[16];+ // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)+ snprintf(alloc_mb, sizeof(alloc_mb), "%zu", allocated / MB_DIVISOR);+ // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)+ snprintf(budget_mb, sizeof(budget_mb), "%zu", g_budget / MB_DIVISOR);+ // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)+ snprintf(pct_str, sizeof(pct_str), "%zu",+ g_budget > 0 ? (allocated * 100) / g_budget : 0);+ cbm_log_warn("mem.pressure.warn", "allocated_mb", alloc_mb, "budget_mb", budget_mb, "pct",+ pct_str);+ } else if (!over && was) {+ /* Transition: over → under */+ atomic_store(&g_was_over, 0);+ char alloc_mb[32];+ char budget_mb[32];+ char pct_str[16];+ // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)+ snprintf(alloc_mb, sizeof(alloc_mb), "%zu", allocated / MB_DIVISOR);+ // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)+ snprintf(budget_mb, sizeof(budget_mb), "%zu", g_budget / MB_DIVISOR);+ // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)+ snprintf(pct_str, sizeof(pct_str), "%zu",+ g_budget > 0 ? (allocated * 100) / g_budget : 0);+ cbm_log_info("mem.pressure.ok", "allocated_mb", alloc_mb, "budget_mb", budget_mb, "pct",+ pct_str);+ }+}++/* ── Update peak ───────────────────────────────────────────────── */++static void update_peak(size_t allocated) {+ size_t old_peak = atomic_load(&g_peak);+ while (allocated > old_peak) {+ if (atomic_compare_exchange_weak(&g_peak, &old_peak, allocated)) {+ break;+ }+ }+}++/* ── Public API ────────────────────────────────────────────────── */++void cbm_vmem_init(double ram_fraction) {+ /* Only first call takes effect */+ int expected = 0;+ if (!atomic_compare_exchange_strong(&g_initialized, &expected, 1)) {+ return;+ }++ if (ram_fraction <= 0.0 || ram_fraction > 1.0) {+ ram_fraction = 0.5;+ }++ cbm_system_info_t info = cbm_system_info();+ g_budget = (size_t)((double)info.total_ram * ram_fraction);++ char budget_mb[32];+ char ram_mb[32];+ // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)+ snprintf(budget_mb, sizeof(budget_mb), "%zu", g_budget / MB_DIVISOR);+ // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)+ snprintf(ram_mb, sizeof(ram_mb), "%zu", info.total_ram / MB_DIVISOR);+ cbm_log_info("vmem.init", "budget_mb", budget_mb, "total_ram_mb", ram_mb);+}++void *cbm_vmem_alloc(size_t size) {+ if (size == 0) {+ return NULL;+ }++ size_t alloc_size = round_to_page(size);++#ifdef _WIN32+ void *ptr = VirtualAlloc(NULL, alloc_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);+#else+ void *ptr = mmap(NULL, alloc_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);+ if (ptr == MAP_FAILED) {+ ptr = NULL;+ }+#endif++ if (!ptr) {+ cbm_log_error("vmem.alloc.fail", "size_mb",+ size > MB_DIVISOR ? "large" : "small");+ return NULL;+ }++ size_t new_total = atomic_fetch_add(&g_allocated, alloc_size) + alloc_size;+ update_peak(new_total);+ check_pressure(new_total);++ return ptr;+}++void cbm_vmem_free(void *ptr, size_t size) {+ if (!ptr || size == 0) {+ return;+ }++ size_t free_size = round_to_page(size);++#ifdef _WIN32+ VirtualFree(ptr, 0, MEM_RELEASE);+#else+ munmap(ptr, free_size);+#endif++ size_t new_total = atomic_fetch_sub(&g_allocated, free_size) - free_size;+ check_pressure(new_total);+}++size_t cbm_vmem_allocated(void) {+ return atomic_load(&g_allocated);+}++size_t cbm_vmem_peak(void) {+ return atomic_load(&g_peak);+}++size_t cbm_vmem_budget(void) {+ return g_budget;+}++bool cbm_vmem_over_budget(void) {+ return atomic_load(&g_allocated) > g_budget;+}++size_t cbm_vmem_worker_budget(int num_workers) {+ if (num_workers <= 0) {+ num_workers = 1;+ }+ return g_budget / (size_t)num_workers;+}diff --git a/src/foundation/vmem.h b/src/foundation/vmem.hnew file mode 100644index 000000000..ccfc7ca3e--- /dev/null+++ b/src/foundation/vmem.h@@ -0,0 +1,50 @@+/*+ * vmem.h — Budget-tracked virtual memory allocator.+ *+ * Allocates via mmap/VirtualAlloc instead of malloc to avoid ptmalloc2's+ * per-thread arena fragmentation (the cause of 321GB VSZ on Linux kernel+ * indexing with 12 workers).+ *+ * Budget: configurable fraction of physical RAM (default 50%). When+ * allocation exceeds the budget, a pressure event is logged. Workers+ * never block — the budget is advisory for monitoring/alerting only.+ *+ * All allocations are page-aligned and zeroed by the OS.+ */+#ifndef CBM_VMEM_H+#define CBM_VMEM_H++#include <stdbool.h>+#include <stddef.h>++/* Initialize vmem with a budget = ram_fraction * total_physical_ram.+ * Thread-safe: only the first call takes effect.+ * Must be called before any cbm_vmem_alloc() calls. */+void cbm_vmem_init(double ram_fraction);++/* Allocate size bytes via mmap/VirtualAlloc.+ * Returns page-aligned, zeroed memory. NULL on failure.+ * Tracks allocation against the budget and logs pressure events. */+void *cbm_vmem_alloc(size_t size);++/* Free memory previously allocated by cbm_vmem_alloc.+ * size must match the original allocation size. */+void cbm_vmem_free(void *ptr, size_t size);++/* Current total allocated bytes (atomic). */+size_t cbm_vmem_allocated(void);++/* Peak allocated bytes seen so far. */+size_t cbm_vmem_peak(void);++/* Total budget in bytes. */+size_t cbm_vmem_budget(void);++/* Returns true if current allocation exceeds the budget. */+bool cbm_vmem_over_budget(void);++/* Per-worker budget hint: budget / num_workers.+ * For monitoring/logging only — workers never block. */+size_t cbm_vmem_worker_budget(int num_workers);++#endif /* CBM_VMEM_H */diff --git a/src/main.c b/src/main.cindex f05662716..3ea85f810 100644--- a/src/main.c+++ b/src/main.c@@ -186,6 +186,10 @@ int main(int argc, char **argv) {}/* Install signal handlers */+#ifdef _WIN32+ signal(SIGTERM, signal_handler);+ signal(SIGINT, signal_handler);+#else// NOLINTNEXTLINE(misc-include-cleaner) — sigaction provided by standard headerstruct sigaction sa = {0};// NOLINTNEXTLINE(misc-include-cleaner) — sa_handler provided by standard header@@ -194,6 +198,7 @@ int main(int argc, char **argv) {sa.sa_flags = 0;sigaction(SIGTERM, &sa, NULL);sigaction(SIGINT, &sa, NULL);+#endif/* Create MCP server */g_server = cbm_mcp_server_new(NULL);diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex 6634a6c3d..5e377344e 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -15,14 +15,15 @@#include "foundation/compat.h"#include "foundation/compat_fs.h"+#ifdef _WIN32+#include <process.h> /* _getpid */+#else#include <unistd.h>#include <sys/unistd.h>#include <sys/poll.h>-#include <yyjson/yyjson.h>--#ifndef _WIN32#include <poll.h>#endif+#include <yyjson/yyjson.h>#include <stdint.h> // int64_t#include <stdio.h>#include <stdlib.h>@@ -1638,7 +1639,11 @@ static char *handle_search_code(cbm_mcp_server_t *srv, const char *args) {/* Write pattern to temp file to avoid shell injection */char tmpfile[256];+#ifdef _WIN32+ snprintf(tmpfile, sizeof(tmpfile), "/tmp/cbm_search_%d.pat", (int)_getpid());+#elsesnprintf(tmpfile, sizeof(tmpfile), "/tmp/cbm_search_%d.pat", (int)getpid());+#endifFILE *tf = fopen(tmpfile, "w");if (!tf) {free(root_path);@@ -1864,7 +1869,7 @@ static char *handle_manage_adr(cbm_mcp_server_t *srv, const char *args) {if (strcmp(mode_str, "update") == 0 && content) {/* Create dir if needed */- mkdir(adr_dir, ADR_DIR_PERMS);+ cbm_mkdir(adr_dir);FILE *fp = fopen(adr_path, "w");if (fp) {(void)fputs(content, fp);diff --git a/src/pipeline/pass_configlink.c b/src/pipeline/pass_configlink.cindex 85ec7d59a..d6bf94936 100644--- a/src/pipeline/pass_configlink.c+++ b/src/pipeline/pass_configlink.c@@ -13,6 +13,7 @@#include "graph_buffer/graph_buffer.h"#include "foundation/hash_table.h"#include "foundation/log.h"+#include "foundation/compat.h"#include <stdint.h>#include <stdio.h>@@ -51,7 +52,7 @@ static bool is_dep_section(const char *s) {"dev-dependencies", "build-dependencies", NULL};for (int i = 0; secs[i]; i++) {// NOLINTNEXTLINE(misc-include-cleaner) — strcasestr provided by standard header- if (strcasestr(s, secs[i]) != NULL) {+ if (cbm_strcasestr(s, secs[i]) != NULL) {return true;}}diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.cindex 5686828ba..3193c1c7e 100644--- a/src/pipeline/pass_parallel.c+++ b/src/pipeline/pass_parallel.c@@ -34,7 +34,7 @@static uint64_t extract_now_ns(void) {struct timespec ts;- clock_gettime(CLOCK_MONOTONIC, &ts);+ cbm_clock_gettime(CLOCK_MONOTONIC, &ts);return ((uint64_t)ts.tv_sec * 1000000000ULL) + (uint64_t)ts.tv_nsec;}diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.cindex 4e27db9b7..7be1335ad 100644--- a/src/pipeline/pipeline.c+++ b/src/pipeline/pipeline.c@@ -47,8 +47,8 @@ struct cbm_pipeline {static double elapsed_ms(struct timespec start) {struct timespec now;- // NOLINTNEXTLINE(misc-include-cleaner) — clock_gettime provided by standard header- clock_gettime(CLOCK_MONOTONIC, &now);+ // NOLINTNEXTLINE(misc-include-cleaner) — cbm_clock_gettime provided by standard header+ cbm_clock_gettime(CLOCK_MONOTONIC, &now);return ((double)(now.tv_sec - start.tv_sec) * CBM_MS_PER_SEC) +((double)(now.tv_nsec - start.tv_nsec) / CBM_US_PER_SEC_F);}@@ -271,7 +271,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {}struct timespec t0;- clock_gettime(CLOCK_MONOTONIC, &t0);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t0);/* Phase 1: Discover files */cbm_discover_opts_t opts = {@@ -310,7 +310,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {.cancelled = &p->cancelled,};- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);rc = pass_structure(p, files, file_count);if (rc != 0) { // cppcheck-suppress knownConditionTrueFalsegoto cleanup;@@ -362,7 +362,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {ctx.prescan_path_map = prescan_map;/* Phase 3A: Parallel extract + definition nodes */- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);rc = cbm_parallel_extract(&ctx, files, file_count, result_cache, &shared_ids, worker_count);cbm_log_info("pass.timing", "pass", "parallel_extract", "elapsed_ms",itoa_buf((int)elapsed_ms(t)));@@ -382,7 +382,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {cbm_gbuf_set_next_id(p->gbuf, atomic_load(&shared_ids));/* Phase 3B: Serial registry build + DEFINES/IMPORTS edges */- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);rc = cbm_build_registry_from_cache(&ctx, files, file_count, result_cache);cbm_log_info("pass.timing", "pass", "registry_build", "elapsed_ms",itoa_buf((int)elapsed_ms(t)));@@ -410,7 +410,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {}/* Phase 4: Parallel resolution (calls + usages + semantic, fused) */- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);rc = cbm_parallel_resolve(&ctx, files, file_count, result_cache, &shared_ids, worker_count);cbm_log_info("pass.timing", "pass", "parallel_resolve", "elapsed_ms",itoa_buf((int)elapsed_ms(t)));@@ -446,7 +446,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {}/* Sequential fallback: original 4-pass chain */- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);rc = cbm_pipeline_pass_definitions(&ctx, files, file_count);if (rc != 0) {goto seq_cleanup;@@ -458,7 +458,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {goto seq_cleanup;}- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);rc = cbm_pipeline_pass_calls(&ctx, files, file_count);if (rc != 0) {goto seq_cleanup;@@ -469,7 +469,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {goto seq_cleanup;}- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);rc = cbm_pipeline_pass_usages(&ctx, files, file_count);if (rc != 0) {goto seq_cleanup;@@ -480,7 +480,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {goto seq_cleanup;}- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);rc = cbm_pipeline_pass_semantic(&ctx, files, file_count);if (rc != 0) {goto seq_cleanup;@@ -509,7 +509,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {}/* Post-extraction passes (shared by both parallel and sequential) */- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);rc = cbm_pipeline_pass_tests(&ctx, files, file_count);if (rc != 0) {goto cleanup;@@ -524,8 +524,8 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {{struct timespec t_gh;struct timespec t_hl;- clock_gettime(CLOCK_MONOTONIC, &t_gh);- clock_gettime(CLOCK_MONOTONIC, &t_hl);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t_gh);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t_hl);cbm_githistory_result_t gh_result = {0};cbm_thread_t gh_thread;@@ -586,14 +586,14 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {/* Pre-dump passes (operate on graph buffer, not store) */if (!check_cancel(p)) {- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);cbm_pipeline_pass_decorator_tags(p->gbuf, p->project_name);cbm_log_info("pass.timing", "pass", "decorator_tags", "elapsed_ms",itoa_buf((int)elapsed_ms(t)));}if (!check_cancel(p)) {- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);cbm_pipeline_pass_configlink(&ctx);cbm_log_info("pass.timing", "pass", "configlink", "elapsed_ms",itoa_buf((int)elapsed_ms(t)));@@ -618,7 +618,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {* Zero SQLite library involvement — cbm_write_db() builds the binary* format directly from flat arrays. Atomic: writes .tmp then renames. */if (!check_cancel(p)) {- clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);// NOLINTNEXTLINE(concurrency-mt-unsafe) — called once during single-threaded dumpconst char *home = getenv("HOME");diff --git a/src/store/store.c b/src/store/store.cindex 379706db7..28e91ed8e 100644--- a/src/store/store.c+++ b/src/store/store.c@@ -142,8 +142,11 @@ static sqlite3_stmt *prepare_cached(cbm_store_t *s, sqlite3_stmt **slot, const cstatic void iso_now(char *buf, size_t sz) {time_t t = time(NULL);struct tm tm;- // NOLINTNEXTLINE(misc-include-cleaner) — gmtime_r provided by standard header+#ifdef _WIN32+ gmtime_s(&tm, &t); /* Windows: reversed arg order */+#elsegmtime_r(&t, &tm);+#endif(void)strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ",&tm); // cert-err33-c: strftime only fails if buffer is too small — 21-byte ISO// timestamp always fits in caller-provided buffers@@ -490,8 +493,7 @@ int cbm_store_dump_to_file(cbm_store_t *s, const char *dest_path) {char *sl = strrchr(dir, '/');if (sl) {*sl = '\0';- // NOLINTNEXTLINE(misc-include-cleaner) — mkdir provided by sys/stat.h- (void)mkdir(dir, 0755);+ (void)cbm_mkdir(dir);}/* Write to temp file for atomic swap */diff --git a/src/ui/embedded_assets.c b/src/ui/embedded_assets.cdeleted file mode 100644index 441c05350..000000000--- a/src/ui/embedded_assets.c+++ /dev/null@@ -1,38 +0,0 @@-/*- * embedded_assets.c — Generated file mapping URL paths to embedded bytes.- * DO NOT EDIT — regenerated by scripts/embed-frontend.sh- */-#include "ui/embedded_assets.h"-#include <string.h>--extern const unsigned char _binary_assets_index_CXGcb5AF_css_data[];-extern const unsigned int _binary_assets_index_CXGcb5AF_css_size;-extern const unsigned char _binary_assets_index_D4itFTv__js_data[];-extern const unsigned int _binary_assets_index_D4itFTv__js_size;-extern const unsigned char _binary_index_html_data[];-extern const unsigned int _binary_index_html_size;--cbm_embedded_file_t CBM_EMBEDDED_FILES[] = {- {"/assets/index-CXGcb5AF.css", _binary_assets_index_CXGcb5AF_css_data, 0, "text/css"},- {"/assets/index-D4itFTv-.js", _binary_assets_index_D4itFTv__js_data, 0,- "application/javascript"},- {"/index.html", _binary_index_html_data, 0, "text/html"},-};-const int CBM_EMBEDDED_FILE_COUNT = 3;--/* Initialize sizes — called once or we use the _size vars directly */-static void __attribute__((constructor)) init_embedded_sizes(void) {- cbm_embedded_file_t *files = CBM_EMBEDDED_FILES;- files[0].size = _binary_assets_index_CXGcb5AF_css_size;- files[1].size = _binary_assets_index_D4itFTv__js_size;- files[2].size = _binary_index_html_size;-}--const cbm_embedded_file_t *cbm_embedded_lookup(const char *path) {- for (int i = 0; i < CBM_EMBEDDED_FILE_COUNT; i++) {- if (strcmp(CBM_EMBEDDED_FILES[i].path, path) == 0) {- return &CBM_EMBEDDED_FILES[i];- }- }- return NULL;-}diff --git a/src/ui/http_server.c b/src/ui/http_server.cindex c544b91a2..a60559b97 100644--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@ -19,6 +19,7 @@/* pipeline.h no longer needed — indexing runs as subprocess */#include "foundation/log.h"#include "foundation/platform.h"+#include "foundation/compat.h"#include "foundation/compat_thread.h"#include <mongoose/mongoose.h>@@ -28,7 +29,11 @@#include <stdio.h>#include <stdlib.h>#include <string.h>-#ifndef _WIN32+#ifdef _WIN32+#include <windows.h>+#include <process.h>+#include <psapi.h> /* GetProcessMemoryInfo */+#else#include <unistd.h>#include <sys/wait.h>#endif@@ -163,7 +168,9 @@ static void handle_logs(struct mg_connection *c, struct mg_http_message *hm) {/* ── Process monitoring ───────────────────────────────────────── */+#ifndef _WIN32#include <sys/resource.h>+#endif#include <signal.h>/* GET /api/processes — list codebase-memory-mcp processes via ps */@@ -171,12 +178,33 @@ static void handle_processes(struct mg_connection *c) {char buf[8192];int pos = 0;- /* Self metrics via getrusage — always available */+#ifdef _WIN32+ /* Windows: GetProcessMemoryInfo + GetProcessTimes */+ PROCESS_MEMORY_COUNTERS pmc;+ FILETIME ft_create, ft_exit, ft_kernel, ft_user;+ double user_s = 0, sys_s = 0;+ size_t rss_bytes = 0;+ if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))+ rss_bytes = pmc.WorkingSetSize;+ if (GetProcessTimes(GetCurrentProcess(), &ft_create, &ft_exit, &ft_kernel, &ft_user)) {+ ULARGE_INTEGER u, k;+ u.LowPart = ft_user.dwLowDateTime;+ u.HighPart = ft_user.dwHighDateTime;+ k.LowPart = ft_kernel.dwLowDateTime;+ k.HighPart = ft_kernel.dwHighDateTime;+ user_s = (double)u.QuadPart / 1e7;+ sys_s = (double)k.QuadPart / 1e7;+ }+ pos += snprintf(buf + pos, sizeof(buf) - (size_t)pos,+ "{\"self_pid\":%d,\"self_rss_mb\":%.1f,"+ "\"self_user_cpu_s\":%.1f,\"self_sys_cpu_s\":%.1f,\"processes\":[]}",+ (int)_getpid(), (double)rss_bytes / (1024.0 * 1024.0), user_s, sys_s);+#elsestruct rusage ru;getrusage(RUSAGE_SELF, &ru);long rss_kb = ru.ru_maxrss;#ifdef __APPLE__- rss_kb /= 1024; /* macOS reports bytes, not KB */+ rss_kb /= 1024;#endifpos += snprintf(buf + pos, sizeof(buf) - (size_t)pos,"{\"self_pid\":%d,\"self_rss_mb\":%.1f,"@@ -185,7 +213,6 @@ static void handle_processes(struct mg_connection *c) {(double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1e6,(double)ru.ru_stime.tv_sec + (double)ru.ru_stime.tv_usec / 1e6);- /* ps for process list — best effort, don't fail if ps is slow */FILE *fp = popen("LC_ALL=C ps -eo pid,pcpu,rss,etime,comm 2>/dev/null"" | grep '[c]odebase-memory-mcp'","r");@@ -199,8 +226,6 @@ static void handle_processes(struct mg_connection *c) {char elapsed[64] = {0};char comm[256] = {0};- /* Use 'comm' (short name) instead of 'command' (full args) to avoid JSON escaping- * issues */if (sscanf(line, "%d %f %ld %63s %255s", &pid, &cpu, &rss, elapsed, comm) >= 4) {if (proc_count > 0)buf[pos++] = ',';@@ -214,8 +239,9 @@ static void handle_processes(struct mg_connection *c) {}pclose(fp);}-pos += snprintf(buf + pos, sizeof(buf) - (size_t)pos, "]}");+#endif+mg_http_reply(c, 200, CORS_HEADERS "Content-Type: application/json\r\n", "%s", buf);}@@ -248,18 +274,33 @@ static void handle_process_kill(struct mg_connection *c, struct mg_http_messageint target_pid = (int)yyjson_get_int(v_pid);yyjson_doc_free(doc);- /* Safety: don't kill ourselves */+#ifdef _WIN32+ if (target_pid == (int)_getpid()) {+#elseif (target_pid == (int)getpid()) {+#endifmg_http_reply(c, 400, CORS_HEADERS "Content-Type: application/json\r\n","{\"error\":\"cannot kill self (use the UI server's own shutdown)\"}");return;}+#ifdef _WIN32+ HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, (DWORD)target_pid);+ if (!hproc || !TerminateProcess(hproc, 1)) {+ if (hproc)+ CloseHandle(hproc);+ mg_http_reply(c, 500, CORS_HEADERS "Content-Type: application/json\r\n",+ "{\"error\":\"kill failed\"}");+ return;+ }+ CloseHandle(hproc);+#elseif (kill(target_pid, SIGTERM) != 0) {mg_http_reply(c, 500, CORS_HEADERS "Content-Type: application/json\r\n","{\"error\":\"kill failed\"}");return;}+#endifmg_http_reply(c, 200, CORS_HEADERS "Content-Type: application/json\r\n", "{\"killed\":%d}",target_pid);@@ -495,7 +536,9 @@ static void *index_thread_fn(void *arg) {const char *bin = g_binary_path;char self_path[1024] = {0};if (!bin[0]) {-#ifdef __APPLE__+#ifdef _WIN32+ GetModuleFileNameA(NULL, self_path, sizeof(self_path));+#elif defined(__APPLE__)uint32_t sz = sizeof(self_path);_NSGetExecutablePath(self_path, &sz);#else@@ -506,13 +549,70 @@ static void *index_thread_fn(void *arg) {bin = self_path[0] ? self_path : "codebase-memory-mcp";}- /* fork+exec: most reliable subprocess control */char log_file[256];- snprintf(log_file, sizeof(log_file), "/tmp/cbm_index_%d.log", (int)getpid());-char json_arg[1200];snprintf(json_arg, sizeof(json_arg), "{\"repo_path\":\"%s\"}", job->root_path);+#ifdef _WIN32+ snprintf(log_file, sizeof(log_file), "%s\\cbm_index_%d.log",+ getenv("TEMP") ? getenv("TEMP") : ".", (int)_getpid());++ /* Build command line for CreateProcess */+ char cmdline[2048];+ snprintf(cmdline, sizeof(cmdline), "\"%s\" cli index_repository \"%s\"", bin, json_arg);++ cbm_log_info("ui.index.spawn", "bin", bin, "log", log_file);++ HANDLE hlog = CreateFileA(log_file, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS,+ FILE_ATTRIBUTE_NORMAL, NULL);+ STARTUPINFOA si_proc = {.cb = sizeof(si_proc)};+ if (hlog != INVALID_HANDLE_VALUE) {+ si_proc.dwFlags = STARTF_USESTDHANDLES;+ si_proc.hStdError = hlog;+ si_proc.hStdOutput = hlog;+ }+ PROCESS_INFORMATION pi = {0};+ if (!CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, NULL, NULL, &si_proc, &pi)) {+ snprintf(job->error_msg, sizeof(job->error_msg), "CreateProcess failed");+ atomic_store(&job->status, 3);+ if (hlog != INVALID_HANDLE_VALUE)+ CloseHandle(hlog);+ return NULL;+ }+ if (hlog != INVALID_HANDLE_VALUE)+ CloseHandle(hlog);++ /* Poll log file while child runs */+ long tail_pos = 0;+ for (;;) {+ DWORD wait = WaitForSingleObject(pi.hProcess, 500);+ FILE *lf = fopen(log_file, "r");+ if (lf) {+ fseek(lf, tail_pos, SEEK_SET);+ char line[512];+ while (fgets(line, sizeof(line), lf)) {+ size_t l = strlen(line);+ if (l > 0 && line[l - 1] == '\n')+ line[l - 1] = '\0';+ if (line[0])+ cbm_ui_log_append(line);+ }+ tail_pos = ftell(lf);+ fclose(lf);+ }+ if (wait == WAIT_OBJECT_0)+ break;+ }++ DWORD win_exit = 1;+ GetExitCodeProcess(pi.hProcess, &win_exit);+ int exit_code = (int)win_exit;+ CloseHandle(pi.hProcess);+ CloseHandle(pi.hThread);+ (void)DeleteFileA(log_file);+#else+ snprintf(log_file, sizeof(log_file), "/tmp/cbm_index_%d.log", (int)getpid());+cbm_log_info("ui.index.fork", "bin", bin, "log", log_file);pid_t child_pid = fork();@@ -523,23 +623,19 @@ static void *index_thread_fn(void *arg) {}if (child_pid == 0) {- /* ── Child process ── */FILE *lf = freopen(log_file, "w", stderr);(void)lf;freopen("/dev/null", "w", stdout);execl(bin, bin, "cli", "index_repository", json_arg, (char *)NULL);- _exit(127); /* exec failed */+ _exit(127);}- /* ── Parent: poll log file while child runs ── */long tail_pos = 0;for (;;) {- /* Check if child exited */int wstatus = 0;pid_t wr = waitpid(child_pid, &wstatus, WNOHANG);bool child_done = (wr == child_pid);- /* Read new lines from log file */FILE *lf = fopen(log_file, "r");if (lf) {fseek(lf, tail_pos, SEEK_SET);@@ -555,20 +651,19 @@ static void *index_thread_fn(void *arg) {fclose(lf);}- if (child_done) {+ if (child_done)break;- }- struct timespec ts = {0, 500000000}; /* 500ms */- nanosleep(&ts, NULL);+ struct timespec ts = {0, 500000000};+ cbm_nanosleep(&ts, NULL);}- /* Get exit code */int wstatus = 0;waitpid(child_pid, &wstatus, 0);int exit_code = WIFEXITED(wstatus) ? WEXITSTATUS(wstatus) : -1;(void)unlink(log_file);+#endifif (exit_code != 0) {snprintf(job->error_msg, sizeof(job->error_msg), "indexing failed (exit code %d)",diff --git a/src/watcher/watcher.c b/src/watcher/watcher.cindex 32d00e821..54da362de 100644--- a/src/watcher/watcher.c+++ b/src/watcher/watcher.c@@ -69,8 +69,8 @@ struct cbm_watcher {static int64_t now_ns(void) {struct timespec ts;- // NOLINTNEXTLINE(misc-include-cleaner) — clock_gettime provided by standard header- clock_gettime(CLOCK_MONOTONIC, &ts);+ // NOLINTNEXTLINE(misc-include-cleaner) — cbm_clock_gettime provided by standard header+ cbm_clock_gettime(CLOCK_MONOTONIC, &ts);return ((int64_t)ts.tv_sec * NS_PER_SEC) + ts.tv_nsec;}diff --git a/test-infrastructure/Dockerfile.mingw b/test-infrastructure/Dockerfile.mingwnew file mode 100644index 000000000..0abec1bad--- /dev/null+++ b/test-infrastructure/Dockerfile.mingw@@ -0,0 +1,25 @@+# Cross-compile for Windows using mingw-w64 — catches all compile errors+# (missing headers, POSIX functions, type mismatches) without needing Windows.+#+# Compiles all source files to .o but does NOT link (Ubuntu's mingw CRT+# differs from MSYS2 UCRT64). Linking is verified by CI on actual Windows.++FROM ubuntu:noble++RUN apt-get update && apt-get install -y --no-install-recommends \+ mingw-w64 make \+ libz-mingw-w64-dev \+ && rm -rf /var/lib/apt/lists/*++WORKDIR /src++# Compile-check: build all objects without linking+ENTRYPOINT ["/bin/bash", "-c"]+CMD ["make -j4 -f Makefile.cbm clean-c && \+ CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ \+ make -j4 -f Makefile.cbm build/c/codebase-memory-mcp \+ CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ \+ 'WIN32_LIBS=-lws2_32 -lpsapi' \+ LDFLAGS='-lm -lstdc++ -lz -lws2_32 -lpsapi -Wl,--allow-multiple-definition' \+ LDFLAGS_TEST='-lm -lstdc++ -lz -lws2_32 -lpsapi -Wl,--allow-multiple-definition' \+ && echo '=== Windows cross-compile: all sources compiled ==='"]diff --git a/test-infrastructure/docker-compose.yml b/test-infrastructure/docker-compose.ymlindex eb65ca019..aa1402109 100644--- a/test-infrastructure/docker-compose.yml+++ b/test-infrastructure/docker-compose.yml@@ -1,15 +1,13 @@-# Local test environment — mirrors GitHub Actions CI for all Docker-capable platforms.+# Local test environment — mirrors GitHub Actions CI for ALL platforms.#-# Coverage matrix:-# Linux arm64: native on Apple Silicon (mirrors CI ubuntu-24.04-arm)-# Linux amd64: QEMU emulation (mirrors CI ubuntu-latest)-# macOS: not possible in Docker — test natively: scripts/test.sh CC=cc-# Windows: not possible in Docker on Mac — CI only-#-# Each platform runs BOTH test (ASan/LeakSan) AND production build (-O2 -Werror).+# Coverage:+# Linux arm64: native test + build (mirrors CI ubuntu-24.04-arm)+# Linux amd64: QEMU test + build (mirrors CI ubuntu-latest)+# Windows: cross-compile with mingw-w64 (catches all compile errors)+# macOS: run natively — scripts/test.sh CC=cc && scripts/build.sh CC=ccservices:- # ── Test builds (ASan + UBSan + LeakSanitizer) ──────────────+ # ── Linux test (ASan + UBSan + LeakSanitizer) ──────────────test:build:context: ..@@ -28,7 +26,7 @@ services:- ..:/srccommand: ["CC=gcc", "CXX=g++"]- # ── Production builds (-O2 -Werror, catches stricter GCC warnings) ──+ # ── Linux production build (-O2 -Werror) ───────────────────build:build:context: ..@@ -49,6 +47,14 @@ services:entrypoint: ["scripts/build.sh"]command: ["CC=gcc", "CXX=g++"]+ # ── Windows cross-compile (mingw-w64, compile-check only) ──+ build-windows:+ build:+ context: ..+ dockerfile: test-infrastructure/Dockerfile.mingw+ volumes:+ - ..:/src+# ── Lint ────────────────────────────────────────────────────lint:build:diff --git a/test-infrastructure/run.sh b/test-infrastructure/run.shindex 1e6a9e144..fd08432d1 100755--- a/test-infrastructure/run.sh+++ b/test-infrastructure/run.sh@@ -1,20 +1,20 @@#!/bin/bash-# Local CI testing — mirrors GitHub Actions for all Docker-capable platforms.+# Local CI — test all platforms before pushing.## Coverage:-# arm64: Native on Apple Silicon (fast, ~3 min)-# amd64: QEMU emulation (slower, ~8 min) — mirrors CI ubuntu-latest-# macOS: Run natively: scripts/test.sh CC=cc CXX=c++-# Windows: CI only (no Docker support on Mac)+# Linux arm64: test (ASan+LeakSan) + build (-O2) [native, fast]+# Linux amd64: test + build [QEMU, slower]+# Windows: cross-compile with mingw-w64 [compile-check]+# macOS: run natively (not in Docker)## Usage:-# ./test-infrastructure/run.sh # test + build arm64 (default)-# ./test-infrastructure/run.sh all # test + build, arm64 + amd64-# ./test-infrastructure/run.sh test # test only (ASan + LeakSan)-# ./test-infrastructure/run.sh build # production build only (-O2 -Werror)-# ./test-infrastructure/run.sh amd64 # test + build amd64 only+# ./test-infrastructure/run.sh # Linux test+build + Windows compile+# ./test-infrastructure/run.sh all # above + amd64+# ./test-infrastructure/run.sh windows # Windows cross-compile only+# ./test-infrastructure/run.sh test # Linux arm64 test only+# ./test-infrastructure/run.sh build # Linux arm64 build only# ./test-infrastructure/run.sh lint # clang-format + cppcheck-# ./test-infrastructure/run.sh shell # debug shell (arm64)+# ./test-infrastructure/run.sh shell # debug shellset -euo pipefail@@ -23,9 +23,12 @@ COMPOSE="docker compose -f $ROOT/test-infrastructure/docker-compose.yml"case "${1:-full}" infull)- echo "=== Linux arm64: test (ASan+LeakSan) + production build (-O2) ==="+ echo "=== Linux arm64: test + build ==="$COMPOSE run --rm test$COMPOSE run --rm build+ echo "=== Windows: cross-compile ==="+ $COMPOSE run --rm build-windows+ echo "=== All passed ===";;test)echo "=== Linux arm64: test (ASan + LeakSanitizer) ==="@@ -35,21 +38,24 @@ case "${1:-full}" inecho "=== Linux arm64: production build (-O2 -Werror) ==="$COMPOSE run --rm build;;+ windows)+ echo "=== Windows: cross-compile (mingw-w64) ==="+ $COMPOSE run --rm build-windows+ ;;amd64)- echo "=== Linux amd64 via QEMU: test + build ==="+ echo "=== Linux amd64: test + build ==="$COMPOSE run --rm test-amd64$COMPOSE run --rm build-amd64;;all)- echo "=== All platforms: test + build ==="- echo "--- arm64 test ---"+ echo "=== Linux arm64: test + build ==="$COMPOSE run --rm test- echo "--- arm64 build ---"$COMPOSE run --rm build- echo "--- amd64 test ---"+ echo "=== Linux amd64: test + build ==="$COMPOSE run --rm test-amd64- echo "--- amd64 build ---"$COMPOSE run --rm build-amd64+ echo "=== Windows: cross-compile ==="+ $COMPOSE run --rm build-windowsecho "=== All platforms passed ===";;lint)@@ -61,7 +67,7 @@ case "${1:-full}" in$COMPOSE run --rm --entrypoint bash test;;*)- echo "Usage: $0 {full|test|build|amd64|all|lint|shell}"+ echo "Usage: $0 {full|test|build|windows|amd64|all|lint|shell}"exit 1;;esacdiff --git a/tests/test_vmem.c b/tests/test_vmem.cnew file mode 100644index 000000000..20e988e88--- /dev/null+++ b/tests/test_vmem.c@@ -0,0 +1,632 @@+/*+ * test_vmem.c — Tests for vmem budget-tracked virtual memory allocator,+ * arena-vmem integration, and slab+vmem parallel extraction.+ */+#include "test_framework.h"+#include "../src/foundation/vmem.h"+#include "../src/foundation/arena.h"+#include "../src/foundation/slab_alloc.h"+#include "pipeline/pipeline.h"+#include "pipeline/pipeline_internal.h"+#include "graph_buffer/graph_buffer.h"+#include "discover/discover.h"+#include "cbm.h"++#include <stdatomic.h>+#include <sys/stat.h>++/* ── vmem basic tests ─────────────────────────────────────────── */++TEST(vmem_budget_zero_before_init) {+ /* Before init, budget should be 0 — arenas/read_file fall back to malloc */+ /* NOTE: vmem_init uses atomic CAS, only first call takes effect.+ * These tests verify the pre-init state if vmem was never initialized,+ * or the post-init state if it was. We test what we can. */+ size_t budget = cbm_vmem_budget();+ /* Budget is either 0 (never inited) or >0 (inited by earlier test/main) */+ (void)budget;+ PASS();+}++TEST(vmem_alloc_and_free) {+ /* Allocate 1MB, write to it, verify, free */+ size_t sz = 1024 * 1024;+ void *p = cbm_vmem_alloc(sz);+ if (!p) {+ /* vmem may not be initialized — skip gracefully */+ PASS();+ }+ /* vmem guarantees zeroed memory */+ unsigned char *bytes = (unsigned char *)p;+ for (size_t i = 0; i < sz; i += 4096) {+ ASSERT_EQ(bytes[i], 0);+ }+ /* Write pattern */+ memset(p, 0xAB, sz);+ ASSERT_EQ(bytes[0], 0xAB);+ ASSERT_EQ(bytes[sz - 1], 0xAB);++ cbm_vmem_free(p, sz);+ PASS();+}++TEST(vmem_alloc_zero_returns_zeroed) {+ size_t sz = 64 * 1024;+ void *p = cbm_vmem_alloc(sz);+ if (!p) {+ PASS();+ }+ unsigned char *bytes = (unsigned char *)p;+ int nonzero = 0;+ for (size_t i = 0; i < sz; i++) {+ if (bytes[i] != 0) {+ nonzero++;+ }+ }+ ASSERT_EQ(nonzero, 0);+ cbm_vmem_free(p, sz);+ PASS();+}++TEST(vmem_budget_tracking) {+ size_t before = cbm_vmem_allocated();+ size_t sz = 256 * 1024;+ void *p = cbm_vmem_alloc(sz);+ if (!p) {+ PASS();+ }+ size_t after = cbm_vmem_allocated();+ /* allocated should have increased (may be rounded to page) */+ ASSERT_GT(after, before);++ cbm_vmem_free(p, sz);+ size_t freed = cbm_vmem_allocated();+ /* Should be back to (approximately) before */+ ASSERT_LTE(freed, before + 4096); /* within one page */+ PASS();+}++TEST(vmem_peak_tracks) {+ size_t sz = 512 * 1024;+ void *p1 = cbm_vmem_alloc(sz);+ if (!p1) {+ PASS();+ }+ size_t peak1 = cbm_vmem_peak();+ ASSERT_GT(peak1, 0);++ void *p2 = cbm_vmem_alloc(sz);+ if (!p2) {+ cbm_vmem_free(p1, sz);+ PASS();+ }+ size_t peak2 = cbm_vmem_peak();+ ASSERT_GTE(peak2, peak1);++ cbm_vmem_free(p2, sz);+ cbm_vmem_free(p1, sz);++ /* Peak should not decrease after free */+ size_t peak3 = cbm_vmem_peak();+ ASSERT_GTE(peak3, peak2);+ PASS();+}++TEST(vmem_worker_budget) {+ size_t budget = cbm_vmem_budget();+ if (budget == 0) {+ /* Not initialized — worker budget should be 0 */+ ASSERT_EQ(cbm_vmem_worker_budget(4), 0);+ PASS();+ }+ /* Budget divides correctly */+ size_t wb4 = cbm_vmem_worker_budget(4);+ size_t wb8 = cbm_vmem_worker_budget(8);+ ASSERT_EQ(wb4, budget / 4);+ ASSERT_EQ(wb8, budget / 8);+ /* Edge case: 0 workers */+ ASSERT_EQ(cbm_vmem_worker_budget(0), 0);+ PASS();+}++/* ── Arena-vmem integration tests ─────────────────────────────── */++TEST(arena_vmem_alloc_and_destroy) {+ /* When vmem is initialized, arena should use vmem for blocks.+ * When not initialized, falls back to malloc. Either way, this must work. */+ CBMArena a;+ cbm_arena_init(&a);+ ASSERT_EQ(a.nblocks, 1);+ /* block_sizes[0] should track the initial block size */+ ASSERT_EQ(a.block_sizes[0], CBM_ARENA_DEFAULT_BLOCK_SIZE);++ /* Allocate some data */+ char *s = cbm_arena_strdup(&a, "hello vmem integration");+ ASSERT_NOT_NULL(s);+ ASSERT_STR_EQ(s, "hello vmem integration");++ cbm_arena_destroy(&a);+ ASSERT_EQ(a.nblocks, 0);+ PASS();+}++TEST(arena_vmem_grow_tracks_sizes) {+ CBMArena a;+ cbm_arena_init_sized(&a, 64);+ ASSERT_EQ(a.block_sizes[0], 64);++ /* Force growth */+ cbm_arena_alloc(&a, 48);+ cbm_arena_alloc(&a, 48); /* triggers grow */+ ASSERT_GTE(a.nblocks, 2);+ /* Second block should be larger */+ ASSERT_GT(a.block_sizes[1], 0);+ ASSERT_GTE(a.block_sizes[1], 96); /* at least min_size */++ cbm_arena_destroy(&a);+ PASS();+}++TEST(arena_vmem_large_alloc) {+ /* Allocate > 64KB to test vmem for larger arena blocks */+ CBMArena a;+ cbm_arena_init(&a);++ size_t big = 128 * 1024;+ void *p = cbm_arena_alloc(&a, big);+ ASSERT_NOT_NULL(p);++ /* Write pattern to verify memory is writable */+ memset(p, 0xCD, big);+ unsigned char *bytes = (unsigned char *)p;+ ASSERT_EQ(bytes[0], 0xCD);+ ASSERT_EQ(bytes[big - 1], 0xCD);++ cbm_arena_destroy(&a);+ PASS();+}++TEST(arena_vmem_reset_frees_blocks) {+ CBMArena a;+ cbm_arena_init_sized(&a, 128);++ /* Create multiple blocks */+ cbm_arena_alloc(&a, 100);+ cbm_arena_alloc(&a, 100);+ ASSERT_GTE(a.nblocks, 2);++ /* Reset should free extra blocks */+ cbm_arena_reset(&a);+ ASSERT_EQ(a.nblocks, 1);+ ASSERT_EQ(a.block_sizes[1], 0); /* freed block's size cleared */++ /* Should still be usable */+ void *p = cbm_arena_alloc(&a, 16);+ ASSERT_NOT_NULL(p);++ cbm_arena_destroy(&a);+ PASS();+}++/* ── Tier 2 slab allocator tests ──────────────────────────── */++TEST(tier2_alloc_and_free_128) {+ /* Allocate 100 bytes — rounds up to 128-byte class (with 16-byte header) */+ cbm_vmem_init(0.5);+ cbm_slab_install();++ void *p = cbm_slab_test_malloc(100);+ ASSERT_NOT_NULL(p);++ /* Verify memory is writable */+ memset(p, 0xAA, 100);+ ASSERT_EQ(((unsigned char *)p)[0], 0xAA);+ ASSERT_EQ(((unsigned char *)p)[99], 0xAA);++ cbm_slab_test_free(p);++ /* Allocate again — should reuse from free list (same size class) */+ void *p2 = cbm_slab_test_malloc(100);+ ASSERT_NOT_NULL(p2);+ /* May or may not be same address, but must be valid */+ memset(p2, 0xBB, 100);+ cbm_slab_test_free(p2);++ cbm_slab_destroy_thread();+ PASS();+}++TEST(tier2_alloc_all_classes) {+ /* Test all 6 size classes: 128, 256, 512, 1024, 2048, 4096 */+ cbm_vmem_init(0.5);+ cbm_slab_install();++ size_t test_sizes[] = {65, 200, 300, 800, 1500, 3000};+ void *ptrs[6];++ for (int i = 0; i < 6; i++) {+ ptrs[i] = cbm_slab_test_malloc(test_sizes[i]);+ ASSERT_NOT_NULL(ptrs[i]);+ /* Write pattern to verify each allocation is independent */+ memset(ptrs[i], (unsigned char)(0x10 + i), test_sizes[i]);+ }++ /* Verify patterns are intact (no overlap) */+ for (int i = 0; i < 6; i++) {+ unsigned char *bytes = (unsigned char *)ptrs[i];+ ASSERT_EQ(bytes[0], (unsigned char)(0x10 + i));+ ASSERT_EQ(bytes[test_sizes[i] - 1], (unsigned char)(0x10 + i));+ }++ /* Free all */+ for (int i = 0; i < 6; i++) {+ cbm_slab_test_free(ptrs[i]);+ }++ cbm_slab_destroy_thread();+ PASS();+}++TEST(tier2_free_list_reuse) {+ /* Verify free list provides O(1) reuse within same size class */+ cbm_vmem_init(0.5);+ cbm_slab_install();++ /* Allocate and free 10 blocks of class 256 */+ void *addrs[10];+ for (int i = 0; i < 10; i++) {+ addrs[i] = cbm_slab_test_malloc(200);+ ASSERT_NOT_NULL(addrs[i]);+ }+ for (int i = 0; i < 10; i++) {+ cbm_slab_test_free(addrs[i]);+ }++ /* Re-allocate 10 blocks — all should come from free list+ * (LIFO order means addrs come back in reverse) */+ for (int i = 0; i < 10; i++) {+ void *p = cbm_slab_test_malloc(200);+ ASSERT_NOT_NULL(p);+ memset(p, 0xCC, 200);+ cbm_slab_test_free(p);+ }++ cbm_slab_destroy_thread();+ PASS();+}++TEST(tier2_oversized_dedicated) {+ /* Allocate >4096 bytes — gets dedicated page, freed immediately on free() */+ cbm_vmem_init(0.5);+ cbm_slab_install();++ size_t before_alloc = cbm_vmem_allocated();++ void *big = cbm_slab_test_malloc(8192);+ ASSERT_NOT_NULL(big);+ memset(big, 0xDD, 8192);++ size_t after_alloc = cbm_vmem_allocated();+ /* vmem allocated should have grown for the dedicated page */+ ASSERT_GT(after_alloc, before_alloc);++ /* Free — dedicated page should be vmem_free'd immediately */+ cbm_slab_test_free(big);++ size_t after_free = cbm_vmem_allocated();+ /* vmem allocated should have decreased (page was freed) */+ ASSERT_LTE(after_free, after_alloc);++ cbm_slab_destroy_thread();+ PASS();+}++TEST(tier2_realloc_same_class) {+ /* realloc within same size class should return same pointer */+ cbm_vmem_init(0.5);+ cbm_slab_install();++ void *p = cbm_slab_test_malloc(100);+ ASSERT_NOT_NULL(p);+ memset(p, 0xEE, 100);++ /* Grow to 110 — still fits in 128-byte class */+ void *p2 = cbm_slab_test_realloc(p, 110);+ ASSERT_NOT_NULL(p2);+ ASSERT_EQ(p, p2); /* same pointer, same class */+ /* Original data should be preserved */+ ASSERT_EQ(((unsigned char *)p2)[0], 0xEE);+ ASSERT_EQ(((unsigned char *)p2)[99], 0xEE);++ /* Shrink to 70 — still fits in 128-byte class */+ void *p3 = cbm_slab_test_realloc(p2, 70);+ ASSERT_NOT_NULL(p3);+ ASSERT_EQ(p2, p3); /* same pointer */++ cbm_slab_test_free(p3);+ cbm_slab_destroy_thread();+ PASS();+}++TEST(tier2_realloc_grows_class) {+ /* realloc to larger class should copy data correctly */+ cbm_vmem_init(0.5);+ cbm_slab_install();++ void *p = cbm_slab_test_malloc(100);+ ASSERT_NOT_NULL(p);+ /* Write known pattern */+ for (int i = 0; i < 100; i++) {+ ((unsigned char *)p)[i] = (unsigned char)(i & 0xFF);+ }++ /* Grow to 300 — moves from class 128 to class 512 */+ void *p2 = cbm_slab_test_realloc(p, 300);+ ASSERT_NOT_NULL(p2);++ /* Verify data was copied */+ unsigned char *bytes = (unsigned char *)p2;+ for (int i = 0; i < 100; i++) {+ ASSERT_EQ(bytes[i], (unsigned char)(i & 0xFF));+ }++ /* Write to the extended area */+ memset(bytes + 100, 0xFF, 200);+ ASSERT_EQ(bytes[299], 0xFF);++ cbm_slab_test_free(p2);+ cbm_slab_destroy_thread();+ PASS();+}++TEST(tier2_realloc_slab_to_tier2) {+ /* realloc from Tier 1 (≤64B) to Tier 2 (>64B) */+ cbm_vmem_init(0.5);+ cbm_slab_install();++ void *p = cbm_slab_test_malloc(32); /* Tier 1 slab */+ ASSERT_NOT_NULL(p);+ memset(p, 0x42, 32);++ /* Promote to Tier 2 */+ void *p2 = cbm_slab_test_realloc(p, 200);+ ASSERT_NOT_NULL(p2);+ /* First 32 bytes should be preserved */+ ASSERT_EQ(((unsigned char *)p2)[0], 0x42);+ ASSERT_EQ(((unsigned char *)p2)[31], 0x42);++ cbm_slab_test_free(p2);+ cbm_slab_destroy_thread();+ PASS();+}++TEST(tier2_calloc_zeroed) {+ /* calloc via tier2 must return zeroed memory */+ cbm_vmem_init(0.5);+ cbm_slab_install();++ void *p = cbm_slab_test_calloc(1, 200);+ ASSERT_NOT_NULL(p);++ /* Verify all bytes are zero */+ unsigned char *bytes = (unsigned char *)p;+ int nonzero = 0;+ for (int i = 0; i < 200; i++) {+ if (bytes[i] != 0) {+ nonzero++;+ }+ }+ ASSERT_EQ(nonzero, 0);++ /* Free and re-calloc — recycled memory must still be zeroed */+ cbm_slab_test_free(p);+ void *p2 = cbm_slab_test_calloc(1, 200);+ ASSERT_NOT_NULL(p2);+ bytes = (unsigned char *)p2;+ nonzero = 0;+ for (int i = 0; i < 200; i++) {+ if (bytes[i] != 0) {+ nonzero++;+ }+ }+ ASSERT_EQ(nonzero, 0);++ cbm_slab_test_free(p2);+ cbm_slab_destroy_thread();+ PASS();+}++TEST(tier2_mixed_alloc_free_stress) {+ /* Stress test: interleaved allocs and frees across Tier 1 and Tier 2 */+ cbm_vmem_init(0.5);+ cbm_slab_install();++ void *ptrs[100];+ size_t sizes[100];++ /* Allocate 100 blocks of varying sizes */+ for (int i = 0; i < 100; i++) {+ sizes[i] = (size_t)(16 + (i * 47) % 4000); /* 16..4000 */+ ptrs[i] = cbm_slab_test_malloc(sizes[i]);+ ASSERT_NOT_NULL(ptrs[i]);+ memset(ptrs[i], (unsigned char)(i & 0xFF), sizes[i]);+ }++ /* Free odd-indexed blocks */+ for (int i = 1; i < 100; i += 2) {+ cbm_slab_test_free(ptrs[i]);+ ptrs[i] = NULL;+ }++ /* Re-allocate freed slots with different sizes */+ for (int i = 1; i < 100; i += 2) {+ sizes[i] = (size_t)(32 + (i * 31) % 2000);+ ptrs[i] = cbm_slab_test_malloc(sizes[i]);+ ASSERT_NOT_NULL(ptrs[i]);+ memset(ptrs[i], (unsigned char)((i + 1) & 0xFF), sizes[i]);+ }++ /* Verify even-indexed blocks still have original data */+ for (int i = 0; i < 100; i += 2) {+ ASSERT_EQ(((unsigned char *)ptrs[i])[0], (unsigned char)(i & 0xFF));+ }++ /* Free all */+ for (int i = 0; i < 100; i++) {+ cbm_slab_test_free(ptrs[i]);+ }++ cbm_slab_destroy_thread();+ PASS();+}++/* ── Slab + vmem parallel extraction test ──────────────────── */++static char g_vmem_tmpdir[256];++static int setup_vmem_test_repo(void) {+ snprintf(g_vmem_tmpdir, sizeof(g_vmem_tmpdir), "/tmp/cbm_vmem_XXXXXX");+ if (!mkdtemp(g_vmem_tmpdir)) {+ return -1;+ }++ char path[512];++ /* Create multiple Go files to force multi-file parallel extraction.+ * We need enough files to exercise slab reset between files on a worker. */+ for (int i = 0; i < 6; i++) {+ snprintf(path, sizeof(path), "%s/file%d.go", g_vmem_tmpdir, i);+ FILE *f = fopen(path, "w");+ if (!f) {+ return -1;+ }+ fprintf(f, "package main\n\nfunc F%d() {\n\tprintln(\"hello\")\n}\n\n"+ "func G%d() int {\n\treturn F%d() + %d\n}\n", i, i, i, i);+ fclose(f);+ }++ /* Add a C file to exercise the preprocessor second-pass path */+ snprintf(path, sizeof(path), "%s/util.c", g_vmem_tmpdir);+ FILE *f = fopen(path, "w");+ if (!f) {+ return -1;+ }+ fprintf(f, "#include <stdio.h>\nvoid util_func(void) { printf(\"hi\"); }\n"+ "int util_add(int a, int b) { return a + b; }\n");+ fclose(f);++ return 0;+}++static void teardown_vmem_test_repo(void) {+ if (g_vmem_tmpdir[0]) {+ char cmd[512];+ snprintf(cmd, sizeof(cmd), "rm -rf '%s'", g_vmem_tmpdir);+ (void)system(cmd);+ g_vmem_tmpdir[0] = '\0';+ }+}++TEST(vmem_parallel_extract_with_slab) {+ /* This test reproduces a SIGSEGV that occurred when:+ * 1. vmem is active (arena + source via mmap)+ * 2. slab allocator is installed (tree-sitter uses slab)+ * 3. slab_reset_thread() was called between files, corrupting+ * the parser's live slab-allocated internal state (subtree pool,+ * stack entries, cached tokens).+ *+ * The fix: don't call slab_reset_thread() between files. Normal+ * slab_free() from ts_tree_delete() returns chunks for reuse.+ * slab_destroy_thread() reclaims everything on worker exit. */+ cbm_vmem_init(0.5);++ if (setup_vmem_test_repo() != 0) {+ SKIP("tmpdir setup failed");+ }++ cbm_discover_opts_t opts = {.mode = CBM_MODE_FULL};+ cbm_file_info_t *files = NULL;+ int file_count = 0;+ if (cbm_discover(g_vmem_tmpdir, &opts, &files, &file_count) != 0) {+ teardown_vmem_test_repo();+ SKIP("discover failed");+ }++ ASSERT_GTE(file_count, 5);++ cbm_gbuf_t *gbuf = cbm_gbuf_new("vmem-test", g_vmem_tmpdir);+ cbm_registry_t *reg = cbm_registry_new();+ atomic_int cancelled;+ atomic_init(&cancelled, 0);++ cbm_pipeline_ctx_t ctx = {+ .project_name = "vmem-test",+ .repo_path = g_vmem_tmpdir,+ .gbuf = gbuf,+ .registry = reg,+ .cancelled = &cancelled,+ };++ _Atomic int64_t shared_ids;+ int64_t gbuf_next = cbm_gbuf_next_id(gbuf);+ atomic_init(&shared_ids, gbuf_next);++ CBMFileResult **result_cache = calloc(file_count, sizeof(CBMFileResult *));+ ASSERT_NOT_NULL(result_cache);++ /* Run parallel extraction with 2 workers — enough to trigger+ * multi-file slab reuse on at least one worker. */+ int rc = cbm_parallel_extract(&ctx, files, file_count, result_cache,+ &shared_ids, 2);+ ASSERT_EQ(rc, 0);++ /* Verify extraction produced results */+ int cached_count = 0;+ for (int i = 0; i < file_count; i++) {+ if (result_cache[i]) {+ cached_count++;+ }+ }+ ASSERT_GTE(cached_count, 5);++ /* Verify nodes were created */+ ASSERT_GT(cbm_gbuf_node_count(gbuf), 0);++ /* Clean up */+ for (int i = 0; i < file_count; i++) {+ if (result_cache[i]) {+ cbm_free_result(result_cache[i]);+ }+ }+ free(result_cache);+ cbm_registry_free(reg);+ cbm_gbuf_free(gbuf);+ cbm_discover_free(files, file_count);+ teardown_vmem_test_repo();+ PASS();+}++SUITE(vmem) {+ RUN_TEST(vmem_budget_zero_before_init);+ RUN_TEST(vmem_alloc_and_free);+ RUN_TEST(vmem_alloc_zero_returns_zeroed);+ RUN_TEST(vmem_budget_tracking);+ RUN_TEST(vmem_peak_tracks);+ RUN_TEST(vmem_worker_budget);+ RUN_TEST(arena_vmem_alloc_and_destroy);+ RUN_TEST(arena_vmem_grow_tracks_sizes);+ RUN_TEST(arena_vmem_large_alloc);+ RUN_TEST(arena_vmem_reset_frees_blocks);+ /* Tier 2 slab allocator tests */+ RUN_TEST(tier2_alloc_and_free_128);+ RUN_TEST(tier2_alloc_all_classes);+ RUN_TEST(tier2_free_list_reuse);+ RUN_TEST(tier2_oversized_dedicated);+ RUN_TEST(tier2_realloc_same_class);+ RUN_TEST(tier2_realloc_grows_class);+ RUN_TEST(tier2_realloc_slab_to_tier2);+ RUN_TEST(tier2_calloc_zeroed);+ RUN_TEST(tier2_mixed_alloc_free_stress);+ /* Integration */+ RUN_TEST(vmem_parallel_extract_with_slab);+}