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
Use memory core for Lens response ownership
Martin Vogela19d7a45fb7e
diff --git a/scripts/memory-core-baseline.txt b/scripts/memory-core-baseline.txtindex 251920e2f..fb46e55e4 100644--- a/scripts/memory-core-baseline.txt+++ b/scripts/memory-core-baseline.txt@@ -52,7 +52,7 @@ src/git/git_context.c 18src/main.c 32src/mcp/compact_out.c 39src/mcp/index_supervisor.c 8-src/mcp/mcp.c 773+src/mcp/mcp.c 769src/pipeline/artifact.c 38src/pipeline/fqn.c 23src/pipeline/lsp_resolve.h 4@@ -78,12 +78,12 @@ src/pipeline/pass_usages.c 4src/pipeline/path_alias.c 42src/pipeline/pipeline.c 134src/pipeline/pipeline_delta.c 19-src/pipeline/pipeline_incremental.c 143+src/pipeline/pipeline_incremental.c 142src/pipeline/registry.c 17src/pipeline/worker_pool.c 2-src/store/store.c 358+src/store/store.c 354src/ui/config.c 12src/ui/http_server.c 31src/ui/httpd.c 21-src/ui/layout3d.c 66+src/ui/layout3d.c 61src/watcher/watcher.c 33diff --git a/src/cli/runtime_settings.c b/src/cli/runtime_settings.cindex c7cb16c91..183656606 100644--- a/src/cli/runtime_settings.c+++ b/src/cli/runtime_settings.c@@ -9,6 +9,8 @@#include "ui/config.h"#include <sqlite3.h>#include <yyjson/yyjson.h>+#include "foundation/mem_core.h"+#include "foundation/json_writer.h"#include <ctype.h>#include <errno.h>#include <limits.h>@@ -599,7 +601,7 @@ static char *snapshot(sqlite3 *db, const char *cache) {}}}- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -627,7 +629,7 @@ static char *error_json(const char *message, int code, int *status) {yyjson_mut_val *root = yyjson_mut_obj(doc);yyjson_mut_doc_set_root(doc, root);json_string(doc, root, "error", message);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -728,7 +730,7 @@ char *cbm_runtime_settings_apply_json(const char *cache, const char *body, size_char *result = ok ? snapshot(db, cache) : NULL;ok = ok && result && sqlite3_exec(db, "COMMIT", NULL, NULL, NULL) == SQLITE_OK;if (!ok) {- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);result = NULL;sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);}diff --git a/src/cli/runtime_settings.h b/src/cli/runtime_settings.hindex 4cbfbabb5..3a9eb5e34 100644--- a/src/cli/runtime_settings.h+++ b/src/cli/runtime_settings.h@@ -10,7 +10,8 @@bool cbm_runtime_settings_init(const char *cache_dir);bool cbm_runtime_settings_initialized(void);-/* JSON API. Returned strings are heap-owned by the caller. HTTP status is+/* JSON API. Returned strings use CBM_MEM_CLASS_OTHER; the caller releases them+ * with cbm_free(CBM_MEM_CLASS_OTHER, json). HTTP status is* 200, 400 (invalid batch), 409 (stale revision), or 500 (storage failure).* A batch either commits completely or changes nothing. */char *cbm_runtime_settings_get_json(const char *cache_dir);diff --git a/src/daemon/application.c b/src/daemon/application.cindex 8155ad48a..ee121b5c6 100644--- a/src/daemon/application.c+++ b/src/daemon/application.c@@ -11,6 +11,7 @@#include "foundation/log.h"#include "foundation/mem.h"#include "foundation/mem_core.h"+#include "foundation/json_writer.h"#include "foundation/platform.h"#include "foundation/secure_random.h"#include "foundation/sha256.h"@@ -335,6 +336,8 @@ typedef struct {} application_default_worker_t;static char *application_index_project_key(const char *root_path, const char *args_json);+static void application_worker_destroy_default(void *context,+ cbm_daemon_application_worker_t opaque);/* Reuse the supervisor's bounded completed-line relay. Only actionable worker* diagnostics enter the daemon journal; ordinary progress stays in worker logs. */@@ -359,19 +362,20 @@ static int application_worker_start_default(void *context, const char *args_jsonconst char *quarantine_file,cbm_daemon_application_worker_t *worker_out) {(void)context;- application_default_worker_t *worker = calloc(1, sizeof(*worker));+ application_default_worker_t *worker = cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*worker));if (!worker) {return -1;}- char *root = cbm_mcp_get_string_arg(args_json, "repo_path");+ yyjson_doc *args_doc = yyjson_read_opts((char *)args_json, strlen(args_json), 0,+ cbm_json_writer_allocator(), NULL);+ const char *root = yyjson_get_str(yyjson_obj_get(yyjson_doc_get_root(args_doc), "repo_path"));worker->project = application_index_project_key(root, args_json);- free(root);+ yyjson_doc_free(args_doc);int result = cbm_index_worker_start_with_log(args_json, memory_budget_bytes, false, marker_file,quarantine_file, application_worker_diagnostic,worker, &worker->handle);if (result != 0) {- free(worker->project);- free(worker);+ application_worker_destroy_default(NULL, worker);*worker_out = NULL;return result;}@@ -407,7 +411,7 @@ static void application_worker_destroy_default(void *context,application_default_worker_t *worker = opaque;cbm_index_worker_destroy(worker->handle);free(worker->project);- free(worker);+ cbm_free(CBM_MEM_CLASS_OTHER, worker);}static uint32_t application_get_u32(const uint8_t *bytes) {@@ -1537,7 +1541,9 @@ static void application_job_execution_cancel(application_job_execution_t *execut* callers, but do not publish a successful UI/background job or retry it as a* crashed worker. Older successful responses may omit isError. */static bool application_index_response_succeeded(const char *response) {- yyjson_doc *document = response ? yyjson_read(response, strlen(response), 0) : NULL;+ yyjson_doc *document = response ? yyjson_read_opts((char *)response, strlen(response), 0,+ cbm_json_writer_allocator(), NULL)+ : NULL;yyjson_val *root = document ? yyjson_doc_get_root(document) : NULL;yyjson_val *error = yyjson_obj_get(root, "isError");bool succeeded = yyjson_is_obj(root) && yyjson_is_arr(yyjson_obj_get(root, "content")) &&@@ -1799,6 +1805,7 @@ static void application_job_publish(cbm_daemon_application_job_t *job,}}application_auto_index_retry_pending_locked(application);+ cbm_mem_class_flush_thread();cbm_mutex_unlock(&application->mutex);}@@ -1865,9 +1872,11 @@ static cbm_daemon_application_job_t *application_find_active_job_locked(}static char *application_index_project_key(const char *root_path, const char *args_json) {- char *override = cbm_mcp_get_string_arg(args_json, "name");+ yyjson_doc *doc = yyjson_read_opts((char *)args_json, strlen(args_json), 0,+ cbm_json_writer_allocator(), NULL);+ const char *override = yyjson_get_str(yyjson_obj_get(yyjson_doc_get_root(doc), "name"));char *key = cbm_project_name_from_path(override && override[0] ? override : root_path);- free(override);+ yyjson_doc_free(doc);return key;}diff --git a/src/foundation/json_writer.h b/src/foundation/json_writer.hnew file mode 100644index 000000000..487c173df--- /dev/null+++ b/src/foundation/json_writer.h@@ -0,0 +1,34 @@+/* JSON output buffers owned by the memory core. */+#ifndef CBM_JSON_WRITER_H+#define CBM_JSON_WRITER_H++#include "foundation/mem_core.h"++#include <yyjson/yyjson.h>++static inline void *cbm_json_writer_malloc(void *ctx, size_t size) {+ (void)ctx;+ return cbm_alloc(CBM_MEM_CLASS_OTHER, size);+}++static inline void *cbm_json_writer_realloc(void *ctx, void *block, size_t old_size, size_t size) {+ (void)ctx;+ (void)old_size;+ return cbm_realloc(CBM_MEM_CLASS_OTHER, block, size);+}++static inline void cbm_json_writer_free(void *ctx, void *block) {+ (void)ctx;+ cbm_free(CBM_MEM_CLASS_OTHER, block);+}++/* Pass this allocator to yyjson_write_opts or yyjson_mut_write_opts. The+ * resulting string must be released with cbm_free(CBM_MEM_CLASS_OTHER, ...).+ * The document itself retains whichever allocator created it. */+static inline const yyjson_alc *cbm_json_writer_allocator(void) {+ static const yyjson_alc allocator = {cbm_json_writer_malloc, cbm_json_writer_realloc,+ cbm_json_writer_free, NULL};+ return &allocator;+}++#endif /* CBM_JSON_WRITER_H */diff --git a/src/foundation/subprocess.c b/src/foundation/subprocess.cindex 4b86feffe..5e3a549ed 100644--- a/src/foundation/subprocess.c+++ b/src/foundation/subprocess.c@@ -10,6 +10,7 @@#include "compat_fs.h"#include "git_env.h" /* strip_git_repo_env: scrubbed child environment for git */#include "log.h"+#include "mem_core.h"#include "platform.h" /* cbm_now_ms */#include "sanitized.h" /* CBM_SANITIZED — spawn-retry budget */@@ -495,9 +496,15 @@ static bool cbm_subprocess_copy_environment(cbm_subprocess_t *process, const chafor (const wchar_t *entry = inherited; *entry; entry += wcslen(entry) + 1) {count++;}- wchar_t **entries = calloc(count + override_count, sizeof(*entries));- wchar_t **converted = calloc(override_count, sizeof(*converted));+ wchar_t **entries = NULL;+ wchar_t **converted = NULL;bool ok = false;+ if (override_count > SIZE_MAX / sizeof(*entries) ||+ count > SIZE_MAX / sizeof(*entries) - override_count) {+ goto done;+ }+ entries = cbm_calloc(CBM_MEM_CLASS_OTHER, (count + override_count) * sizeof(*entries));+ converted = cbm_calloc(CBM_MEM_CLASS_OTHER, override_count * sizeof(*converted));if (!entries || !converted) {goto done;}@@ -509,7 +516,7 @@ static bool cbm_subprocess_copy_environment(cbm_subprocess_t *process, const chaif (process->strip_git_repo_env && cbm_git_env_entry_should_strip(overrides[i])) {continue;}- converted[i] = cbm_utf8_to_wide(overrides[i]);+ converted[i] = cbm_utf8_to_wide_in(CBM_MEM_CLASS_OTHER, overrides[i]);if (!converted[i]) {goto done;}@@ -531,7 +538,7 @@ static bool cbm_subprocess_copy_environment(cbm_subprocess_t *process, const cha}length += entry_length;}- process->environment = calloc(length, sizeof(*process->environment));+ process->environment = cbm_calloc(CBM_MEM_CLASS_OTHER, length * sizeof(*process->environment));if (!process->environment) {goto done;}@@ -545,11 +552,11 @@ static bool cbm_subprocess_copy_environment(cbm_subprocess_t *process, const chadone:if (converted) {for (size_t i = 0; i < override_count; i++) {- free(converted[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, converted[i]);}}- free(converted);- free(entries);+ cbm_free(CBM_MEM_CLASS_OTHER, converted);+ cbm_free(CBM_MEM_CLASS_OTHER, entries);if (process->strip_git_repo_env) {cbm_git_child_env_free(inherited);} else {@@ -562,7 +569,8 @@ static bool cbm_subprocess_copy_environment(cbm_subprocess_t *process, const chasize_t override_count) {#ifdef __APPLE__const char *search_path = getenv("PATH");- process->search_path = cbm_strdup(search_path ? search_path : _PATH_DEFPATH);+ process->search_path =+ cbm_mem_strdup(CBM_MEM_CLASS_OTHER, search_path ? search_path : _PATH_DEFPATH);if (!process->search_path) {return false;}@@ -572,12 +580,17 @@ static bool cbm_subprocess_copy_environment(cbm_subprocess_t *process, const chawhile (inherited && inherited[count]) {count++;}- process->environment = calloc(count + override_count + 1, sizeof(*process->environment));+ if (override_count >= SIZE_MAX / sizeof(*process->environment) ||+ count > SIZE_MAX / sizeof(*process->environment) - override_count - 1) {+ return false;+ }+ process->environment = cbm_calloc(CBM_MEM_CLASS_OTHER,+ (count + override_count + 1) * sizeof(*process->environment));if (!process->environment) {return false;}for (size_t i = 0; i < count; i++) {- process->environment[i] = cbm_strdup(inherited[i]);+ process->environment[i] = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, inherited[i]);if (!process->environment[i]) {return false;}@@ -593,11 +606,11 @@ static bool cbm_subprocess_copy_environment(cbm_subprocess_t *process, const chaprocess->environment[slot][name_length] == '=')) {slot++;}- char *entry = cbm_strdup(overrides[i]);+ char *entry = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, overrides[i]);if (!entry) {return false;}- free(process->environment[slot]);+ cbm_free(CBM_MEM_CLASS_OTHER, process->environment[slot]);process->environment[slot] = entry;if (slot == count) {count++;@@ -620,13 +633,13 @@ static void cbm_subprocess_free_config(cbm_subprocess_t *process) {#ifndef _WIN32if (process->environment) {for (size_t i = 0; process->environment[i]; i++) {- free(process->environment[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, process->environment[i]);}}#endif- free(process->environment);+ cbm_free(CBM_MEM_CLASS_OTHER, process->environment);#ifdef __APPLE__- free(process->search_path);+ cbm_free(CBM_MEM_CLASS_OTHER, process->search_path);#endiffree(process->bin);free(process->windows_cmd_payload);diff --git a/src/mcp/architecture_jobs.c b/src/mcp/architecture_jobs.cindex 5859ae8c1..9ef5c1d39 100644--- a/src/mcp/architecture_jobs.c+++ b/src/mcp/architecture_jobs.c@@ -3,6 +3,8 @@#include "foundation/compat_fs.h"#include "foundation/compat_thread.h"#include "foundation/platform.h"+#include "foundation/mem_core.h"+#include "foundation/json_writer.h"#include <sqlite3.h>#include <yyjson/yyjson.h>#include <stdatomic.h>@@ -48,7 +50,7 @@ struct cbm_architecture_jobs {static char *copy_string(const char *text) {size_t size = strlen(text) + 1;- char *copy = malloc(size);+ char *copy = cbm_alloc(CBM_MEM_CLASS_OTHER, size);if (copy) {memcpy(copy, text, size);}@@ -56,10 +58,10 @@ static char *copy_string(const char *text) {}static void clear_job(arch_job_t *job) {- free(job->path);- free(job->project);- free(job->indexed_at);- free(job->result);+ cbm_free(CBM_MEM_CLASS_OTHER, job->path);+ cbm_free(CBM_MEM_CLASS_OTHER, job->project);+ cbm_free(CBM_MEM_CLASS_OTHER, job->indexed_at);+ cbm_free(CBM_MEM_CLASS_OTHER, job->result);memset(job, 0, sizeof(*job));}@@ -150,20 +152,22 @@ static void *run_projection(void *context) {}}if (error) {- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);result = NULL;}cbm_mutex_lock(&jobs->mutex);job->result = result;job->error = error;job->touched_ms = cbm_now_ms();+ /* The caller may free this worker's retained output after completion. */+ cbm_mem_class_flush_thread();jobs->done = true;cbm_mutex_unlock(&jobs->mutex);return NULL;}cbm_architecture_jobs_t *cbm_architecture_jobs_new(void) {- cbm_architecture_jobs_t *jobs = calloc(1, sizeof(*jobs));+ cbm_architecture_jobs_t *jobs = cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*jobs));if (jobs) {cbm_mutex_init(&jobs->mutex);atomic_init(&jobs->cancelled, false);@@ -184,7 +188,7 @@ void cbm_architecture_jobs_free(cbm_architecture_jobs_t *jobs) {clear_job(&jobs->cache[i]);}cbm_mutex_destroy(&jobs->mutex);- free(jobs);+ cbm_free(CBM_MEM_CLASS_OTHER, jobs);}static char *envelope(const char *status, const char *generation, const char *result,@@ -208,7 +212,7 @@ static char *envelope(const char *status, const char *generation, const char *reyyjson_mut_obj_add_val(doc, root, "result",yyjson_val_mut_copy(doc, yyjson_doc_get_root(payload)));}- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_doc_free(payload);yyjson_mut_doc_free(doc);return json;diff --git a/src/mcp/architecture_jobs.h b/src/mcp/architecture_jobs.hindex 3b0d323ee..989bf4a95 100644--- a/src/mcp/architecture_jobs.h+++ b/src/mcp/architecture_jobs.h@@ -12,7 +12,9 @@ typedef struct cbm_architecture_jobs cbm_architecture_jobs_t;cbm_architecture_jobs_t *cbm_architecture_jobs_new(void);void cbm_architecture_jobs_free(cbm_architecture_jobs_t *jobs);-/* Returns owned JSON: {status, generation, retry_after_ms?, result?, error?}.+/* Returns CBM_MEM_CLASS_OTHER-owned JSON; release it with+ * cbm_free(CBM_MEM_CLASS_OTHER, json).+ * Payload: {status, generation, retry_after_ms?, result?, error?}.* The supplied store is inspected only on the calling thread. */char *cbm_architecture_jobs_request(cbm_architecture_jobs_t *jobs, cbm_store_t *store,const char *project, int64_t entry_node_id);diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex f10ab0cb3..e89120eee 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -73,6 +73,7 @@ enum {#include "watcher/watcher.h"#include "foundation/mem.h"#include "foundation/mem_core.h"+#include "foundation/json_writer.h"#include "foundation/arena.h"#include "foundation/diagnostics.h"#include "foundation/platform.h"@@ -7948,16 +7949,16 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {* caught by the clang-analyzer unix.Malloc lane). */REQUIRE_STORE(store, project);char *scope_path = cbm_mcp_get_string_arg(args, "path");+ yyjson_doc *aspects_doc = NULL;+ char *result = NULL;char *not_indexed = verify_project_indexed(store, project);if (not_indexed) {- free(project);- free(scope_path);- return not_indexed;+ result = not_indexed;+ goto release_arguments;}/* Parse aspects array from args */- yyjson_doc *aspects_doc = NULL;yyjson_val *aspects_arr = NULL;bool include_behavior_evidence = false;{@@ -7967,9 +7968,8 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {yyjson_obj_get(yyjson_doc_get_root(args_doc), "include_behavior_evidence");if (evidence && !yyjson_is_bool(evidence)) {yyjson_doc_free(args_doc);- free(project);- free(scope_path);- return cbm_mcp_text_result("include_behavior_evidence must be a boolean.", true);+ result = cbm_mcp_text_result("include_behavior_evidence must be a boolean.", true);+ goto release_arguments;}include_behavior_evidence = yyjson_get_bool(evidence);yyjson_val *aval = yyjson_obj_get(yyjson_doc_get_root(args_doc), "aspects");@@ -7983,11 +7983,9 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {}if (include_behavior_evidence && !aspect_explicitly_named(aspects_arr, "system_structure")) {- yyjson_doc_free(aspects_doc);- free(project);- free(scope_path);- return cbm_mcp_text_result(+ result = cbm_mcp_text_result("include_behavior_evidence=true requires aspects:[\"system_structure\"].", true);+ goto release_arguments;}/* Build a C string array from aspects for cbm_store_get_architecture.@@ -8025,13 +8023,8 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {char msg[CBM_SZ_512];snprintf(msg, sizeof(msg), "Unknown aspect '%s'. Valid: %s.", aspects_strs[i],valid_list);- char *err = cbm_mcp_text_result(msg, true);- free(project);- free(scope_path);- if (aspects_doc) {- yyjson_doc_free(aspects_doc);- }- return err;+ result = cbm_mcp_text_result(msg, true);+ goto release_arguments;}}@@ -8063,11 +8056,9 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {reply = cbm_mcp_text_result(json ? json : "Architecture request allocation failed.",json == NULL);}- free(json);- free(project);- free(scope_path);- yyjson_doc_free(aspects_doc);- return reply;+ cbm_free(CBM_MEM_CLASS_OTHER, json);+ result = reply;+ goto release_arguments;}/* Default (no aspects) = compact summary. The old default rendered ALL@@ -8384,16 +8375,11 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {cbm_store_architecture_free(&arch);cbm_store_schema_free(&schema);- if (aspects_doc) {- yyjson_doc_free(aspects_doc);- }- free(project);- free(scope_path);free(norm_path);char *text = cbm_sb_finish(&sb);- char *result = cbm_mcp_text_result(text ? text : "out of memory", text == NULL);+ result = cbm_mcp_text_result(text ? text : "out of memory", text == NULL);free(text);- return result;+ goto release_arguments;}yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);@@ -8641,15 +8627,14 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {yyjson_mut_doc_free(doc);cbm_store_architecture_free(&arch);cbm_store_schema_free(&schema);- if (aspects_doc) {- yyjson_doc_free(aspects_doc);- }- free(project);- free(scope_path);free(norm_path);- char *result = cbm_mcp_text_result(json, false);+ result = cbm_mcp_text_result(json, false);free(json);+release_arguments:+ yyjson_doc_free(aspects_doc);+ free(project);+ free(scope_path);return result;}@@ -19552,17 +19537,19 @@ enum {static char *handle_ingest_traces(cbm_mcp_server_t *srv, const char *args) {char *project = get_project_arg(args);bool mutation_held = false;+ yyjson_doc *adoc = NULL;+ cbm_store_t *owned_rw = NULL;+ char *result = NULL;if (project) {mutation_held = mcp_project_mutation_begin(srv, project);if (!mutation_held) {- free(project);- return cbm_mcp_text_result("project operation cancelled or blocked by an active index",- true);+ result = cbm_mcp_text_result(+ "project operation cancelled or blocked by an active index", true);+ goto release_request;}if (mcp_request_cancelled(srv)) {- mcp_project_mutation_end(srv, project);- free(project);- return cbm_mcp_text_result("project operation cancelled for this request", true);+ result = cbm_mcp_text_result("project operation cancelled for this request", true);+ goto release_request;}}@@ -19571,30 +19558,21 @@ static char *handle_ingest_traces(cbm_mcp_server_t *srv, const char *args) {cbm_store_t *store = resolve_store(srv, project);if (!store) {char *error = build_no_store_error_checked(srv, project);- char *result = cbm_mcp_text_result(error, true);+ result = cbm_mcp_text_result(error, true);free(error);- if (mutation_held) {- mcp_project_mutation_end(srv, project);- }- free(project);- return result;+ goto release_request;}- yyjson_doc *adoc = yyjson_read(args, strlen(args), 0);+ adoc = yyjson_read_opts((char *)args, strlen(args), 0, cbm_json_writer_allocator(), NULL);yyjson_val *aroot = adoc ? yyjson_doc_get_root(adoc) : NULL;yyjson_val *traces = aroot ? yyjson_obj_get(aroot, "traces") : NULL;size_t trace_count = traces && yyjson_is_arr(traces) ? yyjson_arr_size(traces) : 0U;if (trace_count == 0U || trace_count > INGEST_TRACES_MAX) {- if (adoc)- yyjson_doc_free(adoc);- if (mutation_held) {- mcp_project_mutation_end(srv, project);- }- free(project);- return cbm_mcp_text_result(+ result = cbm_mcp_text_result("traces is required: a non-empty array (max 10000) of {path: [qualified_name, ...]} ""or {caller, callee} entries",true);+ goto release_request;}const char *label = yyjson_get_str(yyjson_obj_get(aroot, "label"));if (!label || !label[0])@@ -19603,15 +19581,10 @@ static char *handle_ingest_traces(cbm_mcp_server_t *srv, const char *args) {/* resolve_store opens file-backed projects query-only (and skips schema* DDL); observation writes need the dedicated read-write connection —* whose open also creates the observed_* tables in pre-existing DBs. */- cbm_store_t *owned_rw = NULL;store = open_store_for_write(srv, store, &owned_rw);if (!store) {- yyjson_doc_free(adoc);- if (mutation_held) {- mcp_project_mutation_end(srv, project);- }- free(project);- return cbm_mcp_text_result("could not open the project store for writing", true);+ result = cbm_mcp_text_result("could not open the project store for writing", true);+ goto release_request;}struct sqlite3 *db = cbm_store_get_db(store);@@ -19620,14 +19593,8 @@ static char *handle_ingest_traces(cbm_mcp_server_t *srv, const char *args) {"SELECT 1 FROM nodes WHERE project=?1 AND qualified_name=?2 ""LIMIT 1",-1, &exists, NULL) != SQLITE_OK) {- if (owned_rw)- cbm_store_close(owned_rw);- yyjson_doc_free(adoc);- if (mutation_held) {- mcp_project_mutation_end(srv, project);- }- free(project);- return cbm_mcp_text_result("store is not queryable", true);+ result = cbm_mcp_text_result("store is not queryable", true);+ goto release_request;}long long pairs_stored = 0, pairs_unmatched = 0, paths_stored = 0, malformed = 0;@@ -19704,12 +19671,13 @@ static char *handle_ingest_traces(cbm_mcp_server_t *srv, const char *args) {pairs_stored++;}if (path) {- char *path_json = yyjson_val_write(path, 0, NULL);+ char *path_json =+ yyjson_val_write_opts(path, 0, cbm_json_writer_allocator(), NULL, NULL);if (path_json) {if (cbm_store_observed_upsert_path(store, project, path_json, label, count) ==CBM_STORE_OK)paths_stored++;- free(path_json);+ cbm_free(CBM_MEM_CLASS_OTHER, path_json);}}}@@ -19732,7 +19700,7 @@ static char *handle_ingest_traces(cbm_mcp_server_t *srv, const char *args) {break; /* the current run alone exceeds the cap; stop here */}- yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_doc *doc = yyjson_mut_doc_new(cbm_json_writer_allocator());yyjson_mut_val *root = yyjson_mut_obj(doc);yyjson_mut_doc_set_root(doc, root);yyjson_mut_obj_add_str(doc, root, "status", "stored");@@ -19750,8 +19718,13 @@ static char *handle_ingest_traces(cbm_mcp_server_t *srv, const char *args) {if (evicted_runs > 0)yyjson_mut_obj_add_int(doc, root, "evicted_runs", evicted_runs);- char *json = yy_doc_to_str(doc);+ char *json = root && yy_mut_normalize_output_text(doc, root, true)+ ? yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL)+ : NULL;yyjson_mut_doc_free(doc);+ result = cbm_mcp_text_result(json, false);+ cbm_free(CBM_MEM_CLASS_OTHER, json);+release_request:yyjson_doc_free(adoc);if (owned_rw)cbm_store_close(owned_rw);@@ -19760,8 +19733,6 @@ static char *handle_ingest_traces(cbm_mcp_server_t *srv, const char *args) {}free(project);- char *result = cbm_mcp_text_result(json, false);- free(json);return result;}diff --git a/src/store/architecture_projection.c b/src/store/architecture_projection.cindex 51cc54e7c..9bfc2d3b4 100644--- a/src/store/architecture_projection.c+++ b/src/store/architecture_projection.c@@ -2,6 +2,7 @@#include "store/architecture_projection.h"#include "foundation/hash_table.h"#include "foundation/platform.h"+#include "foundation/mem_core.h"#include <sqlite3.h>#include <yyjson/yyjson.h>#include <limits.h>@@ -41,7 +42,7 @@ static void *ap_json_malloc(void *context, size_t size) {budget->failed = true;return NULL;}- void *p = malloc(size);+ void *p = cbm_alloc(CBM_MEM_CLASS_OTHER, size);if (p)budget->allocated += size;else@@ -56,7 +57,7 @@ static void *ap_json_realloc(void *context, void *ptr, size_t old_size, size_t sbudget->failed = true;return NULL;}- void *p = realloc(ptr, size);+ void *p = cbm_realloc(CBM_MEM_CLASS_OTHER, ptr, size);if (p)budget->allocated += growth;else@@ -66,7 +67,7 @@ static void *ap_json_realloc(void *context, void *ptr, size_t old_size, size_t sstatic void ap_json_free(void *context, void *ptr) {(void)context;- free(ptr);+ cbm_free(CBM_MEM_CLASS_OTHER, ptr);}/* Presence and references are deliberately separate from execution. */@@ -157,7 +158,7 @@ static char *ap_copy(ap_context *c, const unsigned char *text) {c->limited = "Indexed symbol text exceeds the analysis memory budget.";return NULL;}- char *result = malloc(bytes);+ char *result = cbm_alloc(CBM_MEM_CLASS_OTHER, bytes);if (!result)return NULL;memcpy(result, s, bytes);@@ -278,7 +279,8 @@ static int ap_counts(ap_context *c, const char *project) {* keep their handlers. Indexed entry points stay ahead of handlers. */static int ap_route_handlers(ap_context *c) {enum { AP_PRODUCTION_REGISTRAR = 1, AP_TEST_REGISTRAR = 2 };- unsigned char *registrars = calloc((size_t)c->n + 1, sizeof(*registrars));+ unsigned char *registrars =+ cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(*registrars));if (!registrars) {return CBM_STORE_ERR;}@@ -297,7 +299,7 @@ static int ap_route_handlers(ap_context *c) {handler->handler = true;}}- free(registrars);+ cbm_free(CBM_MEM_CLASS_OTHER, registrars);return CBM_STORE_OK;}@@ -314,8 +316,8 @@ static void ap_classify(ap_node *n) {}static int ap_load(ap_context *c, const char *project) {- c->nodes = calloc((size_t)c->total_nodes + 1, sizeof(*c->nodes));- c->edges = calloc((size_t)c->total_edges + 1, sizeof(*c->edges));+ c->nodes = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->total_nodes + 1) * sizeof(*c->nodes));+ c->edges = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->total_edges + 1) * sizeof(*c->edges));if (!c->nodes || !c->edges)return CBM_STORE_ERR;sqlite3_stmt *stmt = NULL;@@ -419,7 +421,7 @@ static int ap_ownership(ap_context *c) {}/* QN ownership is an indexed declaration match, not a path heuristic. */size_t len = strlen(n->qn);- char *qn = malloc(len + 1);+ char *qn = cbm_alloc(CBM_MEM_CLASS_OTHER, len + 1);if (!qn) {rc = CBM_STORE_ERR;break;@@ -436,7 +438,7 @@ static int ap_ownership(ap_context *c) {break;}}- free(qn);+ cbm_free(CBM_MEM_CLASS_OTHER, qn);/* Embedded tests can share a production file/class, but not its* architecture atom. Prefer a same-role file declaration if present. */if (n->test != c->nodes[n->atom].test)@@ -468,19 +470,19 @@ static int ap_pair_compare(const void *a, const void *b) {* have a fixed atom-size ceiling. These remain component candidates. */static int ap_components(ap_context *c) {int n = c->n;- int *group = malloc(((size_t)n + 1) * sizeof(int));- int *sizes = calloc((size_t)n + 1, sizeof(int));- int *offset = calloc((size_t)n + 2, sizeof(int));- int *score = calloc((size_t)n + 1, sizeof(int));- int *touched = malloc(((size_t)n + 1) * sizeof(int));- ap_pair *pairs = malloc(((size_t)c->m * 2 + 1) * sizeof(*pairs));+ int *group = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 1) * sizeof(int));+ int *sizes = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 1) * sizeof(int));+ int *offset = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 2) * sizeof(int));+ int *score = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 1) * sizeof(int));+ int *touched = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 1) * sizeof(int));+ ap_pair *pairs = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->m * 2 + 1) * sizeof(*pairs));if (!group || !sizes || !offset || !score || !touched || !pairs) {- free(group);- free(sizes);- free(offset);- free(score);- free(touched);- free(pairs);+ cbm_free(CBM_MEM_CLASS_OTHER, group);+ cbm_free(CBM_MEM_CLASS_OTHER, sizes);+ cbm_free(CBM_MEM_CLASS_OTHER, offset);+ cbm_free(CBM_MEM_CLASS_OTHER, score);+ cbm_free(CBM_MEM_CLASS_OTHER, touched);+ cbm_free(CBM_MEM_CLASS_OTHER, pairs);return CBM_STORE_ERR;}for (int i = 0; i < n; i++)@@ -546,7 +548,7 @@ static int ap_components(ap_context *c) {if (!changed)break;}- c->components = calloc((size_t)n + 1, sizeof(*c->components));+ c->components = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 1) * sizeof(*c->components));if (!c->components) {rc = CBM_STORE_ERR;goto finish;@@ -588,10 +590,10 @@ static int ap_components(ap_context *c) {}/* Count unique file memberships, including isolated files. */CBMHashTable *seen = cbm_ht_create((uint32_t)n);- char **keys = calloc((size_t)n + 1, sizeof(char *));+ char **keys = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 1) * sizeof(char *));if (!seen || !keys) {cbm_ht_free(seen);- free(keys);+ cbm_free(CBM_MEM_CLASS_OTHER, keys);rc = CBM_STORE_ERR;goto finish;}@@ -601,7 +603,7 @@ static int ap_components(ap_context *c) {if (node->component < 0 || !node->file[0])continue;size_t len = strlen(node->file) + 32;- char *key = malloc(len);+ char *key = cbm_alloc(CBM_MEM_CLASS_OTHER, len);if (!key) {rc = CBM_STORE_ERR;break;@@ -612,19 +614,19 @@ static int ap_components(ap_context *c) {keys[key_count++] = key;c->components[node->component].files++;} else- free(key);+ cbm_free(CBM_MEM_CLASS_OTHER, key);}cbm_ht_free(seen);for (int i = 0; i < key_count; i++)- free(keys[i]);- free(keys);+ cbm_free(CBM_MEM_CLASS_OTHER, keys[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, keys);finish:- free(group);- free(sizes);- free(offset);- free(score);- free(touched);- free(pairs);+ cbm_free(CBM_MEM_CLASS_OTHER, group);+ cbm_free(CBM_MEM_CLASS_OTHER, sizes);+ cbm_free(CBM_MEM_CLASS_OTHER, offset);+ cbm_free(CBM_MEM_CLASS_OTHER, score);+ cbm_free(CBM_MEM_CLASS_OTHER, touched);+ cbm_free(CBM_MEM_CLASS_OTHER, pairs);return rc;}@@ -679,8 +681,8 @@ static int ap_overview_grouping(ap_context *c) {}for (int depth = 2; depth >= 0; depth--) {for (int g = 0; g < c->group_count; g++) {- free(c->groups[g].id);- free(c->groups[g].label);+ cbm_free(CBM_MEM_CLASS_OTHER, c->groups[g].id);+ cbm_free(CBM_MEM_CLASS_OTHER, c->groups[g].label);}c->group_count = 0;bool retry = false;@@ -702,7 +704,7 @@ static int ap_overview_grouping(ap_context *c) {}bool test = c->nodes[part->root].test;size_t bytes = length + 32;- char *key = malloc(bytes);+ char *key = cbm_alloc(CBM_MEM_CLASS_OTHER, bytes);if (!key)return CBM_STORE_ERR;snprintf(key, bytes, "%s:%s:%.*s", part->directory ? "directory" : "unlocated",@@ -713,7 +715,7 @@ static int ap_overview_grouping(ap_context *c) {break;if (g == c->group_count) {if (g >= 64) {- free(key);+ cbm_free(CBM_MEM_CLASS_OTHER, key);retry = true;break;}@@ -728,11 +730,11 @@ static int ap_overview_grouping(ap_context *c) {snprintf(key, bytes, "(root)");group->label = ap_copy(c, (const unsigned char *)key);if (!group->id || !group->label) {- free(key);+ cbm_free(CBM_MEM_CLASS_OTHER, key);return CBM_STORE_ERR;}}- free(key);+ cbm_free(CBM_MEM_CLASS_OTHER, key);part->overview_group = g;c->groups[g].components++;c->groups[g].members += part->members;@@ -746,10 +748,10 @@ static int ap_overview_grouping(ap_context *c) {}/* File counts are unique within a group; component file counts can overlap. */CBMHashTable *seen = cbm_ht_create((uint32_t)c->n);- char **keys = calloc((size_t)c->n + 1, sizeof(*keys));+ char **keys = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(*keys));if (!seen || !keys) {cbm_ht_free(seen);- free(keys);+ cbm_free(CBM_MEM_CLASS_OTHER, keys);return CBM_STORE_ERR;}int count = 0, rc = CBM_STORE_OK;@@ -759,14 +761,14 @@ static int ap_overview_grouping(ap_context *c) {continue;int g = c->components[node->component].overview_group;size_t length = strlen(node->file) + 32;- char *key = malloc(length);+ char *key = cbm_alloc(CBM_MEM_CLASS_OTHER, length);if (!key) {rc = CBM_STORE_ERR;break;}snprintf(key, length, "%d:%s", g, node->file);if (cbm_ht_has(seen, key))- free(key);+ cbm_free(CBM_MEM_CLASS_OTHER, key);else {cbm_ht_set(seen, key, (void *)1);keys[count++] = key;@@ -779,8 +781,8 @@ static int ap_overview_grouping(ap_context *c) {}cbm_ht_free(seen);for (int i = 0; i < count; i++)- free(keys[i]);- free(keys);+ cbm_free(CBM_MEM_CLASS_OTHER, keys[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, keys);return rc;}@@ -796,11 +798,12 @@ static yyjson_val *ap_symbol_properties(ap_context *c, int index) {if (c->metadata_budget.failed)return NULL;if (!c->symbol_properties) {- c->symbol_properties = calloc((size_t)c->n, sizeof(*c->symbol_properties));- c->symbol_properties_loaded = calloc((size_t)c->n, 1);+ c->symbol_properties =+ cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n) * sizeof(*c->symbol_properties));+ c->symbol_properties_loaded = cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)c->n);if (!c->symbol_properties || !c->symbol_properties_loaded) {- free(c->symbol_properties);- free(c->symbol_properties_loaded);+ cbm_free(CBM_MEM_CLASS_OTHER, c->symbol_properties);+ cbm_free(CBM_MEM_CLASS_OTHER, c->symbol_properties_loaded);c->symbol_properties = NULL;c->symbol_properties_loaded = NULL;c->metadata_budget.failed = true;@@ -1068,23 +1071,23 @@ static yyjson_mut_val *ap_witness(yyjson_mut_doc *doc, ap_context *c, int edge)static int ap_cycles(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *cycles, const ap_dep *deps,int count) {int n = c->component_count;- int *out = calloc((size_t)n + 2, sizeof(int));- int *in = calloc((size_t)n + 2, sizeof(int));- int *forward = malloc(((size_t)count + 1) * sizeof(int));- int *reverse = malloc(((size_t)count + 1) * sizeof(int));- int *cursor = calloc((size_t)n + 1, sizeof(int));- int *stack = malloc(((size_t)n + 1) * sizeof(int));- int *order = malloc(((size_t)n + 1) * sizeof(int));- unsigned char *seen = calloc((size_t)n + 1, 1);+ int *out = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 2) * sizeof(int));+ int *in = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 2) * sizeof(int));+ int *forward = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)count + 1) * sizeof(int));+ int *reverse = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)count + 1) * sizeof(int));+ int *cursor = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 1) * sizeof(int));+ int *stack = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 1) * sizeof(int));+ int *order = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)n + 1) * sizeof(int));+ unsigned char *seen = cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)n + 1);if (!out || !in || !forward || !reverse || !cursor || !stack || !order || !seen) {- free(out);- free(in);- free(forward);- free(reverse);- free(cursor);- free(stack);- free(order);- free(seen);+ cbm_free(CBM_MEM_CLASS_OTHER, out);+ cbm_free(CBM_MEM_CLASS_OTHER, in);+ cbm_free(CBM_MEM_CLASS_OTHER, forward);+ cbm_free(CBM_MEM_CLASS_OTHER, reverse);+ cbm_free(CBM_MEM_CLASS_OTHER, cursor);+ cbm_free(CBM_MEM_CLASS_OTHER, stack);+ cbm_free(CBM_MEM_CLASS_OTHER, order);+ cbm_free(CBM_MEM_CLASS_OTHER, seen);return CBM_STORE_ERR;}for (int i = 0; i < count; i++) {@@ -1172,14 +1175,14 @@ static int ap_cycles(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *cycles,}}done:- free(out);- free(in);- free(forward);- free(reverse);- free(cursor);- free(stack);- free(order);- free(seen);+ cbm_free(CBM_MEM_CLASS_OTHER, out);+ cbm_free(CBM_MEM_CLASS_OTHER, in);+ cbm_free(CBM_MEM_CLASS_OTHER, forward);+ cbm_free(CBM_MEM_CLASS_OTHER, reverse);+ cbm_free(CBM_MEM_CLASS_OTHER, cursor);+ cbm_free(CBM_MEM_CLASS_OTHER, stack);+ cbm_free(CBM_MEM_CLASS_OTHER, order);+ cbm_free(CBM_MEM_CLASS_OTHER, seen);return rc;}@@ -1203,21 +1206,22 @@ static int ap_path_candidate_compare(const void *left, const void *right) {* tree stays linear in graph size; we never enumerate all possible paths. */static int ap_paths(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *paths, const int *entries,int entry_count, bool *truncated) {- int *offset = calloc((size_t)c->n + 2, sizeof(int));- int *adj = malloc(((size_t)c->m + 1) * sizeof(int));- int *cursor = calloc((size_t)c->n + 1, sizeof(int));- int *queue = malloc(((size_t)c->n + 1) * sizeof(int));- int *previous = malloc(((size_t)c->n + 1) * sizeof(int));- int *depth = calloc((size_t)c->n + 1, sizeof(int));- ap_path_candidate *candidates = malloc(((size_t)c->n + 1) * sizeof(*candidates));+ int *offset = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 2) * sizeof(int));+ int *adj = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->m + 1) * sizeof(int));+ int *cursor = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int));+ int *queue = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int));+ int *previous = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int));+ int *depth = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int));+ ap_path_candidate *candidates =+ cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(*candidates));if (!offset || !adj || !cursor || !queue || !previous || !depth || !candidates) {- free(offset);- free(adj);- free(cursor);- free(queue);- free(previous);- free(depth);- free(candidates);+ cbm_free(CBM_MEM_CLASS_OTHER, offset);+ cbm_free(CBM_MEM_CLASS_OTHER, adj);+ cbm_free(CBM_MEM_CLASS_OTHER, cursor);+ cbm_free(CBM_MEM_CLASS_OTHER, queue);+ cbm_free(CBM_MEM_CLASS_OTHER, previous);+ cbm_free(CBM_MEM_CLASS_OTHER, depth);+ cbm_free(CBM_MEM_CLASS_OTHER, candidates);return CBM_STORE_ERR;}for (int i = 0; i < c->m; i++)@@ -1325,13 +1329,13 @@ static int ap_paths(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *paths, c}}done:- free(offset);- free(adj);- free(cursor);- free(queue);- free(previous);- free(depth);- free(candidates);+ cbm_free(CBM_MEM_CLASS_OTHER, offset);+ cbm_free(CBM_MEM_CLASS_OTHER, adj);+ cbm_free(CBM_MEM_CLASS_OTHER, cursor);+ cbm_free(CBM_MEM_CLASS_OTHER, queue);+ cbm_free(CBM_MEM_CLASS_OTHER, previous);+ cbm_free(CBM_MEM_CLASS_OTHER, depth);+ cbm_free(CBM_MEM_CLASS_OTHER, candidates);return rc;}@@ -1440,7 +1444,7 @@ static int ap_overview(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *root)if ((i & 255) == 0 && ap_stopped(c))return CBM_STORE_ERR;}- ap_dep *edges = malloc(((size_t)c->m + 1) * sizeof(*edges));+ ap_dep *edges = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->m + 1) * sizeof(*edges));if (!edges)return CBM_STORE_ERR;int count = 0;@@ -1472,11 +1476,11 @@ static int ap_overview(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *root)}i = end;if (ap_stopped(c)) {- free(edges);+ cbm_free(CBM_MEM_CLASS_OTHER, edges);return CBM_STORE_ERR;}}- free(edges);+ cbm_free(CBM_MEM_CLASS_OTHER, edges);}yyjson_mut_obj_add_bool(doc, overview, "complete",!c->limited && shown == connection_count && !omitted_entries);@@ -1493,15 +1497,15 @@ static int ap_overview(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *root)static int ap_symbol_cycles(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *cycles,const int *out, const int *in, const int *forward, const int *reverse,const bool *nodes, const bool *edges) {- int *stack = malloc(((size_t)c->n + 1) * sizeof(int));- int *cursor = malloc(((size_t)c->n + 1) * sizeof(int));- int *order = malloc(((size_t)c->n + 1) * sizeof(int));- bool *seen = calloc((size_t)c->n + 1, sizeof(bool));+ int *stack = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int));+ int *cursor = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int));+ int *order = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int));+ bool *seen = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(bool));if (!stack || !cursor || !order || !seen) {- free(stack);- free(cursor);- free(order);- free(seen);+ cbm_free(CBM_MEM_CLASS_OTHER, stack);+ cbm_free(CBM_MEM_CLASS_OTHER, cursor);+ cbm_free(CBM_MEM_CLASS_OTHER, order);+ cbm_free(CBM_MEM_CLASS_OTHER, seen);return CBM_STORE_ERR;}memcpy(cursor, out, ((size_t)c->n + 1) * sizeof(int));@@ -1568,10 +1572,10 @@ static int ap_symbol_cycles(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *}}done:- free(stack);- free(cursor);- free(order);- free(seen);+ cbm_free(CBM_MEM_CLASS_OTHER, stack);+ cbm_free(CBM_MEM_CLASS_OTHER, cursor);+ cbm_free(CBM_MEM_CLASS_OTHER, order);+ cbm_free(CBM_MEM_CLASS_OTHER, seen);return rc;}@@ -1608,17 +1612,18 @@ static int ap_behavior(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *root,yyjson_mut_obj_add_int(doc, totals, "corridor_edges", 0);return CBM_STORE_OK;}- int *out = calloc((size_t)c->n + 2, sizeof(int)), *in = calloc((size_t)c->n + 2, sizeof(int));- int *forward = malloc(((size_t)c->m + 1) * sizeof(int)),- *reverse = malloc(((size_t)c->m + 1) * sizeof(int));- int *queue = malloc(((size_t)c->n + 1) * sizeof(int)),- *cursor = malloc(((size_t)c->n + 1) * sizeof(int));- int *distance = malloc(((size_t)c->n + 1) * sizeof(int)),- *back = malloc(((size_t)c->n + 1) * sizeof(int));- int *previous = malloc(((size_t)c->n + 1) * sizeof(int)),- *next = malloc(((size_t)c->n + 1) * sizeof(int));- bool *keep_nodes = calloc((size_t)c->n + 1, sizeof(bool)),- *keep_edges = calloc((size_t)c->m + 1, sizeof(bool));+ int *out = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 2) * sizeof(int)),+ *in = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 2) * sizeof(int));+ int *forward = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->m + 1) * sizeof(int)),+ *reverse = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->m + 1) * sizeof(int));+ int *queue = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int)),+ *cursor = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int));+ int *distance = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int)),+ *back = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int));+ int *previous = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int)),+ *next = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(int));+ bool *keep_nodes = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->n + 1) * sizeof(bool)),+ *keep_edges = cbm_calloc(CBM_MEM_CLASS_OTHER, ((size_t)c->m + 1) * sizeof(bool));int rc = CBM_STORE_OK, reachable = 0, kept_nodes = 0, kept_edges = 0, target_count = 0;bool complete = true, corridor_complete = true;if (!out || !in || !forward || !reverse || !queue || !cursor || !distance || !back ||@@ -1796,18 +1801,18 @@ static int ap_behavior(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *root,yyjson_mut_obj_add_int(doc, totals, "corridor_edges", kept_edges);done:c->evidence_scope = AP_EVIDENCE_CONTEXT;- free(out);- free(in);- free(forward);- free(reverse);- free(queue);- free(cursor);- free(distance);- free(back);- free(previous);- free(next);- free(keep_nodes);- free(keep_edges);+ cbm_free(CBM_MEM_CLASS_OTHER, out);+ cbm_free(CBM_MEM_CLASS_OTHER, in);+ cbm_free(CBM_MEM_CLASS_OTHER, forward);+ cbm_free(CBM_MEM_CLASS_OTHER, reverse);+ cbm_free(CBM_MEM_CLASS_OTHER, queue);+ cbm_free(CBM_MEM_CLASS_OTHER, cursor);+ cbm_free(CBM_MEM_CLASS_OTHER, distance);+ cbm_free(CBM_MEM_CLASS_OTHER, back);+ cbm_free(CBM_MEM_CLASS_OTHER, previous);+ cbm_free(CBM_MEM_CLASS_OTHER, next);+ cbm_free(CBM_MEM_CLASS_OTHER, keep_nodes);+ cbm_free(CBM_MEM_CLASS_OTHER, keep_edges);return rc;}@@ -1847,7 +1852,8 @@ static int ap_render(ap_context *c, const char *project, char **out_json) {/* Prefer the largest connected candidates, retaining deterministic IDs.* Never relabel discarded components as a single invented component.* The same rank picks the overview entries, before they render. */- ap_rank *ranks = malloc(((size_t)c->component_count + 1) * sizeof(*ranks));+ ap_rank *ranks =+ cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->component_count + 1) * sizeof(*ranks));if (!ranks) {rc = CBM_STORE_ERR;goto done;@@ -1860,7 +1866,7 @@ static int ap_render(ap_context *c, const char *project, char **out_json) {for (int pick = 0; pick < c->options.max_components && pick < c->component_count; pick++)c->components[ranks[pick].index].displayed = shown++;ap_list_overview(c, ranks);- free(ranks);+ cbm_free(CBM_MEM_CLASS_OTHER, ranks);if (ap_stopped(c)) {rc = CBM_STORE_ERR;goto done;@@ -1900,7 +1906,7 @@ static int ap_render(ap_context *c, const char *project, char **out_json) {p->members - (p->sample_count > 0 ? 1 : 0));yyjson_mut_arr_add_val(parts, part);}- deps = malloc(((size_t)c->m + 1) * sizeof(*deps));+ deps = cbm_alloc(CBM_MEM_CLASS_OTHER, ((size_t)c->m + 1) * sizeof(*deps));if (!deps) {rc = CBM_STORE_ERR;goto done;@@ -2065,7 +2071,7 @@ static int ap_render(ap_context *c, const char *project, char **out_json) {rc = budget.failed ? CBM_STORE_SCAN_LIMIT : CBM_STORE_ERR;}done:- free(deps);+ cbm_free(CBM_MEM_CLASS_OTHER, deps);yyjson_mut_doc_free(doc);return rc;}@@ -2139,26 +2145,26 @@ int cbm_store_architecture_projection(cbm_store_t *store, const char *project,if (transaction)sqlite3_exec(c.db, "ROLLBACK", NULL, NULL, NULL);for (int i = 0; i < c.n; i++) {- free(c.nodes[i].name);- free(c.nodes[i].qn);- free(c.nodes[i].file);- free(c.nodes[i].label);+ cbm_free(CBM_MEM_CLASS_OTHER, c.nodes[i].name);+ cbm_free(CBM_MEM_CLASS_OTHER, c.nodes[i].qn);+ cbm_free(CBM_MEM_CLASS_OTHER, c.nodes[i].file);+ cbm_free(CBM_MEM_CLASS_OTHER, c.nodes[i].label);if (c.symbol_properties)yyjson_doc_free(c.symbol_properties[i]);}- free(c.symbol_properties);- free(c.symbol_properties_loaded);+ cbm_free(CBM_MEM_CLASS_OTHER, c.symbol_properties);+ cbm_free(CBM_MEM_CLASS_OTHER, c.symbol_properties_loaded);for (int i = 0; i < c.component_count; i++)- free(c.components[i].directory);+ cbm_free(CBM_MEM_CLASS_OTHER, c.components[i].directory);for (int i = 0; i < c.group_count; i++) {- free(c.groups[i].id);- free(c.groups[i].label);+ cbm_free(CBM_MEM_CLASS_OTHER, c.groups[i].id);+ cbm_free(CBM_MEM_CLASS_OTHER, c.groups[i].label);}- free(c.nodes);- free(c.edges);- free(c.components);+ cbm_free(CBM_MEM_CLASS_OTHER, c.nodes);+ cbm_free(CBM_MEM_CLASS_OTHER, c.edges);+ cbm_free(CBM_MEM_CLASS_OTHER, c.components);if (c.cancelled) {- free(*out_json);+ cbm_free(CBM_MEM_CLASS_OTHER, *out_json);*out_json = NULL;return CBM_STORE_CANCELLED;}diff --git a/src/store/architecture_projection.h b/src/store/architecture_projection.hindex f472fa4db..83cabdfdb 100644--- a/src/store/architecture_projection.h+++ b/src/store/architecture_projection.h@@ -26,7 +26,8 @@ typedef struct {* Requires exclusive use of the store connection (prefer a dedicated worker* connection). Installs and removes its SQLite progress handler. No parsing,* indexing, database writes, or runtime execution observations are performed.- * Returns malloc-owned JSON on OK, including explicit status="limited" when+ * Returns CBM_MEM_CLASS_OTHER-owned JSON on OK; release it with+ * cbm_free(CBM_MEM_CLASS_OTHER, json). Includes explicit status="limited" when* graph/resource limits prevent a complete projection. Cancel returns* CBM_STORE_CANCELLED, unknown projects return CBM_STORE_NOT_FOUND.* Component membership is inferred; every dependency witness is an indexeddiff --git a/src/store/store.c b/src/store/store.cindex 8bc471e89..f2f40e11a 100644--- a/src/store/store.c+++ b/src/store/store.c@@ -13,6 +13,7 @@#include "foundation/constants.h"#include "foundation/arena.h"#include "foundation/hash_table.h"+#include "foundation/mem_core.h"#include "foundation/sha256.h"#include <math.h>@@ -9616,7 +9617,7 @@ int cbm_leiden(const int64_t *nodes, int node_count, const cbm_louvain_edge_t *eint n = node_count;double gamma = resolution > 0.0 ? resolution : 1.0;- cbm_louvain_result_t *result = malloc((size_t)n * sizeof(*result));+ cbm_louvain_result_t *result = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)n * sizeof(*result));if (!result) {return CBM_NOT_FOUND;}@@ -9961,7 +9962,7 @@ static int arch_clusters(cbm_store_t *s, const char *project, const char *path,}}}- free(res);+ cbm_free(CBM_MEM_CLASS_OTHER, res);if (comm && C > 0) {/* 4. Members + cohesion (internal vs boundary edges) per community. */diff --git a/src/store/store.h b/src/store/store.hindex d9d409265..8721853c5 100644--- a/src/store/store.h+++ b/src/store/store.h@@ -1234,7 +1234,8 @@ typedef struct {* the partition can no longer be coarsened. Refinement guarantees every* reported community is internally connected. The resolution parameter* controls granularity (higher -> more, smaller communities); 1.0 is standard.- * Allocates *out (length *out_count == node_count); the caller frees it. */+ * Allocates *out (length *out_count == node_count) in CBM_MEM_CLASS_OTHER;+ * the caller releases it with cbm_free(CBM_MEM_CLASS_OTHER, *out). */int cbm_leiden(const int64_t *nodes, int node_count, const cbm_louvain_edge_t *edges,int edge_count, double resolution, cbm_louvain_result_t **out, int *out_count);diff --git a/src/ui/activity.c b/src/ui/activity.cindex 56bf09b88..f8c7233c5 100644--- a/src/ui/activity.c+++ b/src/ui/activity.c@@ -1,5 +1,7 @@#include "ui/activity.h"#include <yyjson/yyjson.h>+#include "foundation/mem_core.h"+#include "foundation/json_writer.h"#include <stdio.h>#include <stdlib.h>#include <string.h>@@ -282,7 +284,7 @@ int cbm_activity_ui_log(sqlite3 *db, const char *line, bool historical) {}static char *write_reply(yyjson_mut_doc *doc) {- char *reply = yyjson_mut_write(doc, 0, NULL);+ char *reply = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return reply;}@@ -432,7 +434,7 @@ int cbm_activity_ingest(sqlite3 *db, const char *body, char **reply) {}char *payload = write_reply(clean);if (!payload || strlen(payload) > EVENT_MAX) {- free(payload);+ cbm_free(CBM_MEM_CLASS_OTHER, payload);ok = false;break;}@@ -444,7 +446,7 @@ int cbm_activity_ingest(sqlite3 *db, const char *body, char **reply) {ok = sqlite3_step(st) == SQLITE_DONE;if (ok)accepted += sqlite3_changes(db);- free(payload);+ cbm_free(CBM_MEM_CLASS_OTHER, payload);}sqlite3_finalize(st);if (ok)diff --git a/src/ui/activity.h b/src/ui/activity.hindex 816516b72..8033a83c6 100644--- a/src/ui/activity.h+++ b/src/ui/activity.h@@ -12,9 +12,11 @@ bool cbm_activity_log(sqlite3 *db, const char *line);/* Canonical frontend writer: 1 inserted/repaired, 0 duplicate, -1 unavailable.* Historical import never assigns a project to previously unknown evidence. */int cbm_activity_ui_log(sqlite3 *db, const char *line, bool historical);+/* All JSON replies below use CBM_MEM_CLASS_OTHER; release them with+ * cbm_free(CBM_MEM_CLASS_OTHER, json). */char *cbm_activity_ui_logs(sqlite3 *db, int limit, const char *path, const char *export_path,const char *previous_path);-/* Returns HTTP status. Replies are heap allocated, caller frees them. */+/* Returns HTTP status. Replies have the same JSON ownership as above. */int cbm_activity_ingest(sqlite3 *db, const char *body, char **reply);char *cbm_activity_agents(sqlite3 *db, const char *project, int64_t after, int limit);char *cbm_activity_logs(sqlite3 *db, int64_t after, int limit, int min_level);diff --git a/src/ui/atlas.h b/src/ui/atlas.hindex 41e7a0b22..564f2501d 100644--- a/src/ui/atlas.h+++ b/src/ui/atlas.h@@ -9,9 +9,21 @@#define CBM_UI_ATLAS_H#include "store/store.h"+#include "foundation/mem_core.h"#include <stdint.h>+/* Internal UI buffers, including returned JSON/HTML and region-name copies,+ * are charged to OTHER. Release with cbm_free(CBM_MEM_CLASS_OTHER, ...).+ * yyjson documents retain their own allocator and use yyjson_*_doc_free. */++/* cbm_calloc takes bytes; retain calloc's array-overflow rejection. */+static inline void *cbm_atlas_calloc_array(size_t count, size_t element_size) {+ if (element_size && count > SIZE_MAX / element_size)+ return NULL;+ return cbm_calloc(CBM_MEM_CLASS_OTHER, count * element_size);+}+/* ── Modules tree (GET /api/tree) ─────────────────────────────────* Aggregated children of one folder: sub-folders with file/symbol counts,* files directly inside it, per-child dominant region and missed-coverage@@ -103,12 +115,13 @@ void cbm_atlas_impact_analysis_shutdown(void);/* Attach runtime observation (observed_calls) to a trace ("path") or* flow-detail ("steps") JSON: observed hops gain {count, label,* last_seen}; unobserved hops stay merely possible. Takes ownership of- * `json` and returns it (or a replacement). */+ * `json` (allocated in OTHER) and returns it (or a replacement in OTHER). */char *cbm_atlas_attach_observed(cbm_store_t *store, const char *project, char *json);/* ── Region lookups (layout_regions.c) ────────────────────────────* Cache-backed; computing on first use. name_out (optional) receives a- * heap copy the caller frees. Returns region id or -1. */+ * copy the caller releases with cbm_free(CBM_MEM_CLASS_OTHER, ...).+ * Returns region id or -1. */int cbm_layout_region_for_file(cbm_store_t *store, const char *project, const char *file_path,char **name_out);diff --git a/src/ui/atlas_api.c b/src/ui/atlas_api.cindex 0f4a3cf84..cd4b10296 100644--- a/src/ui/atlas_api.c+++ b/src/ui/atlas_api.c@@ -4,6 +4,7 @@* http_server.c; tests call these directly).*/#include "foundation/constants.h"+#include "foundation/json_writer.h"#include "ui/atlas.h"#include "foundation/hash_table.h"@@ -22,7 +23,7 @@ static char *aa_strdup(const char *s) {if (!s)return NULL;size_t len = strlen(s) + 1;- char *copy = malloc(len);+ char *copy = cbm_alloc(CBM_MEM_CLASS_OTHER, len);if (copy)memcpy(copy, s, len);return copy;@@ -99,7 +100,8 @@ static aa_tree_child_t *aa_child(aa_children_t *set, const char *name, bool is_f}if (set->count >= set->cap) {int nc = set->cap ? set->cap * 2 : 64;- aa_tree_child_t *grown = realloc(set->items, (size_t)nc * sizeof(aa_tree_child_t));+ aa_tree_child_t *grown =+ cbm_realloc(CBM_MEM_CLASS_OTHER, set->items, (size_t)nc * sizeof(aa_tree_child_t));if (!grown)return NULL;/* The by_name table stores indices, so growth is safe. */@@ -140,17 +142,17 @@ static void aa_children_free(aa_children_t *set) {int cap;} box;box.cap = set->count * 2 + 8;- box.keys = malloc((size_t)box.cap * sizeof(char *));+ box.keys = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)box.cap * sizeof(char *));box.count = 0;if (set->by_name && box.keys)cbm_ht_foreach(set->by_name, aa_collect_keys, &box);for (int i = 0; i < box.count; i++)- free(box.keys[i]);- free(box.keys);+ cbm_free(CBM_MEM_CLASS_OTHER, box.keys[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, box.keys);cbm_ht_free(set->by_name);for (int i = 0; i < set->count; i++)- free(set->items[i].name);- free(set->items);+ cbm_free(CBM_MEM_CLASS_OTHER, set->items[i].name);+ cbm_free(CBM_MEM_CLASS_OTHER, set->items);memset(set, 0, sizeof(*set));}@@ -278,7 +280,7 @@ char *cbm_atlas_tree_json(cbm_store_t *store, const char *project, const char *pyyjson_mut_arr_append(arr, obj);}yyjson_mut_obj_add_val(doc, root, "children", arr);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);aa_children_free(&set);return json;@@ -490,7 +492,7 @@ char *cbm_atlas_symbol_json(cbm_store_t *store, const char *project, int64_t nodyyjson_mut_obj_add_strcpy(doc, robj, "name", region_name);yyjson_mut_obj_add_val(doc, root, "region", robj);}- free(region_name);+ cbm_free(CBM_MEM_CLASS_OTHER, region_name);}aa_add_connections(doc, root, db, store, project, id, true, limit, offset);@@ -616,7 +618,7 @@ char *cbm_atlas_symbol_json(cbm_store_t *store, const char *project, int64_t nodyyjson_mut_obj_add_val(doc, root, "file_history", copy);yyjson_doc_free(hdoc);}- free(history);+ cbm_free(CBM_MEM_CLASS_OTHER, history);}}@@ -648,8 +650,8 @@ char *cbm_atlas_symbol_json(cbm_store_t *store, const char *project, int64_t nodyyjson_mut_obj_add_val(doc, root, "similar", similar);}- free(file_copy);- char *json = yyjson_mut_write(doc, 0, NULL);+ cbm_free(CBM_MEM_CLASS_OTHER, file_copy);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -668,7 +670,7 @@ char *cbm_atlas_scent_json(cbm_store_t *store, const char *project, const char *return NULL;enum { SCENT_MAX_MATCHES = 50000, SCENT_MAX_REGIONS = 4096 };- long long *counts = calloc(SCENT_MAX_REGIONS, sizeof(long long));+ long long *counts = cbm_atlas_calloc_array(SCENT_MAX_REGIONS, sizeof(long long));if (!counts)return NULL;long long total = 0, unmapped = 0;@@ -694,7 +696,7 @@ char *cbm_atlas_scent_json(cbm_store_t *store, const char *project, const char *"ESCAPE '\\' COLLATE NOCASE AND file_path IS NOT NULL ""AND label NOT IN ('File','Folder')",-1, &st, NULL) != SQLITE_OK) {- free(counts);+ cbm_free(CBM_MEM_CLASS_OTHER, counts);return NULL;}sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);@@ -731,8 +733,8 @@ char *cbm_atlas_scent_json(cbm_store_t *store, const char *project, const char *yyjson_mut_arr_append(arr, row);}yyjson_mut_obj_add_val(doc, root, "regions", arr);- free(counts);- char *json = yyjson_mut_write(doc, 0, NULL);+ cbm_free(CBM_MEM_CLASS_OTHER, counts);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -806,13 +808,14 @@ char *cbm_atlas_bridges_json(cbm_store_t *store, const char *project) {if (!node) {if (all_count >= all_cap) {int nc = all_cap ? all_cap * 2 : 256;- br_node_t **grown = realloc(all, (size_t)nc * sizeof(br_node_t *));+ br_node_t **grown =+ cbm_realloc(CBM_MEM_CLASS_OTHER, all, (size_t)nc * sizeof(br_node_t *));if (!grown)continue;all = grown;all_cap = nc;}- node = calloc(1, sizeof(br_node_t));+ node = cbm_atlas_calloc_array(1, sizeof(br_node_t));if (!node)continue;node->id = ids[k];@@ -872,14 +875,14 @@ char *cbm_atlas_bridges_json(cbm_store_t *store, const char *project) {}sqlite3_finalize(nst);}- free(node);+ cbm_free(CBM_MEM_CLASS_OTHER, node);}yyjson_mut_obj_add_val(doc, root, "bridges", arr);for (int i = 0; i < all_count; i++)- free(all[i]);- free(all);+ cbm_free(CBM_MEM_CLASS_OTHER, all[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, all);cbm_ht_free(ht);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -893,20 +896,20 @@ char *cbm_atlas_blast_json(cbm_store_t *store, const char *project, const char *return NULL;enum { BL_MAX_REGIONS = 4096, BL_MAX_FILES = 200 };- long long *counts = calloc(BL_MAX_REGIONS, sizeof(long long));- char **names = calloc(BL_MAX_REGIONS, sizeof(char *));+ long long *counts = cbm_atlas_calloc_array(BL_MAX_REGIONS, sizeof(long long));+ char **names = cbm_atlas_calloc_array(BL_MAX_REGIONS, sizeof(char *));if (!counts || !names) {- free(counts);- free(names);+ cbm_free(CBM_MEM_CLASS_OTHER, counts);+ cbm_free(CBM_MEM_CLASS_OTHER, names);return NULL;}int files = 0, unmapped = 0;bool truncated = false;- char *copy = strdup(files_csv);+ char *copy = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, files_csv);if (!copy) {- free(counts);- free(names);+ cbm_free(CBM_MEM_CLASS_OTHER, counts);+ cbm_free(CBM_MEM_CLASS_OTHER, names);return NULL;}char *cursor = copy;@@ -920,7 +923,7 @@ char *cbm_atlas_blast_json(cbm_store_t *store, const char *project, const char *break;}files++;- char *region_name = NULL; /* strdup'd by the lookup — we own it */+ char *region_name = NULL; /* OTHER copy from the lookup; owned here. */int region = cbm_layout_region_for_file(store, project, cursor, ®ion_name);if (region >= 0 && region < BL_MAX_REGIONS) {counts[region]++;@@ -931,11 +934,11 @@ char *cbm_atlas_blast_json(cbm_store_t *store, const char *project, const char *} else {unmapped++;}- free(region_name);+ cbm_free(CBM_MEM_CLASS_OTHER, region_name);}cursor = comma ? comma + 1 : NULL;}- free(copy);+ cbm_free(CBM_MEM_CLASS_OTHER, copy);yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);yyjson_mut_val *root = yyjson_mut_obj(doc);@@ -953,12 +956,12 @@ char *cbm_atlas_blast_json(cbm_store_t *store, const char *project, const char *yyjson_mut_obj_add_strcpy(doc, row, "name", names[i]);yyjson_mut_obj_add_int(doc, row, "count", counts[i]);yyjson_mut_arr_append(arr, row);- free(names[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, names[i]);}yyjson_mut_obj_add_val(doc, root, "regions", arr);- free(counts);- free(names);- char *json = yyjson_mut_write(doc, 0, NULL);+ cbm_free(CBM_MEM_CLASS_OTHER, counts);+ cbm_free(CBM_MEM_CLASS_OTHER, names);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}diff --git a/src/ui/atlas_flows.c b/src/ui/atlas_flows.cindex acc325958..755e1ceab 100644--- a/src/ui/atlas_flows.c+++ b/src/ui/atlas_flows.c@@ -14,6 +14,7 @@* ratio bonus: callees outweigh callers*/#include "foundation/constants.h"+#include "foundation/json_writer.h"#include "ui/atlas.h"#include "foundation/hash_table.h"@@ -88,7 +89,7 @@ static char *fl_strdup(const char *s) {if (!s)return NULL;size_t len = strlen(s) + 1;- char *copy = malloc(len);+ char *copy = cbm_alloc(CBM_MEM_CLASS_OTHER, len);if (copy)memcpy(copy, s, len);return copy;@@ -96,17 +97,17 @@ static char *fl_strdup(const char *s) {static void flow_cache_clear_locked(void) {for (int i = 0; i < g_flow_cache.node_count; i++) {- free(g_flow_cache.nodes[i].name);- free(g_flow_cache.nodes[i].file_path);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.nodes[i].name);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.nodes[i].file_path);}- free(g_flow_cache.nodes);- free(g_flow_cache.out_edges);- free(g_flow_cache.in_first);- free(g_flow_cache.in_edges);- free(g_flow_cache.data_first);- free(g_flow_cache.data_count);- free(g_flow_cache.data_edges);- free(g_flow_cache.flows);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.nodes);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.out_edges);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.in_first);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.in_edges);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.data_first);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.data_count);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.data_edges);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.flows);memset(&g_flow_cache, 0, sizeof(g_flow_cache));}@@ -223,7 +224,7 @@ static void fl_walk(const flow_cache_t *cache, flow_t *flow, int32_t entry) {memset(flow, 0, sizeof(*flow));flow->entry = entry;flow->terminal = entry;- bool *visited = calloc((size_t)cache->node_count, sizeof(bool));+ bool *visited = cbm_atlas_calloc_array((size_t)cache->node_count, sizeof(bool));if (!visited)return;@@ -293,7 +294,7 @@ static void fl_walk(const flow_cache_t *cache, flow_t *flow, int32_t entry) {stack[sp++] = (frame_t){picked[m], step, (uint8_t)(frame.depth + 1)};}}- free(visited);+ cbm_free(CBM_MEM_CLASS_OTHER, visited);}static int fl_rebuild_locked(cbm_store_t *store, const char *project, const char *key) {@@ -319,7 +320,8 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const charwhile (sqlite3_step(st) == SQLITE_ROW) {if (n >= cap) {int nc = cap ? cap * 2 : 4096;- flow_node_t *grown = realloc(nodes, (size_t)nc * sizeof(flow_node_t));+ flow_node_t *grown =+ cbm_realloc(CBM_MEM_CLASS_OTHER, nodes, (size_t)nc * sizeof(flow_node_t));if (!grown)break;nodes = grown;@@ -342,17 +344,17 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const charg_flow_cache.callable_total = n;if (n > FLOW_NODE_CAP) {for (int i = 0; i < n; i++) {- free(nodes[i].name);- free(nodes[i].file_path);+ cbm_free(CBM_MEM_CLASS_OTHER, nodes[i].name);+ cbm_free(CBM_MEM_CLASS_OTHER, nodes[i].file_path);}- free(nodes);+ cbm_free(CBM_MEM_CLASS_OTHER, nodes);g_flow_cache.nodes = NULL;}snprintf(g_flow_cache.key, sizeof(g_flow_cache.key), "%s", key);return 0;}- fl_id_idx_t *idmap = malloc((size_t)n * sizeof(fl_id_idx_t));+ fl_id_idx_t *idmap = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)n * sizeof(fl_id_idx_t));if (!idmap) {g_flow_cache.nodes = nodes;g_flow_cache.node_count = n;@@ -379,11 +381,11 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const charcontinue;if (ne >= ecap) {int nc = ecap ? ecap * 2 : 8192;- int32_t *ns = realloc(src, (size_t)nc * sizeof(int32_t));- int32_t *nd = realloc(dst, (size_t)nc * sizeof(int32_t));+ int32_t *ns = cbm_realloc(CBM_MEM_CLASS_OTHER, src, (size_t)nc * sizeof(int32_t));+ int32_t *nd = cbm_realloc(CBM_MEM_CLASS_OTHER, dst, (size_t)nc * sizeof(int32_t));if (!ns || !nd) {- free(ns ? ns : src);- free(nd ? nd : dst);+ cbm_free(CBM_MEM_CLASS_OTHER, ns ? ns : src);+ cbm_free(CBM_MEM_CLASS_OTHER, nd ? nd : dst);src = dst = NULL;ne = 0;break;@@ -414,11 +416,11 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const charcontinue;if (dne >= dcap) {int nc = dcap ? dcap * 2 : 1024;- int32_t *ns = realloc(dsrc, (size_t)nc * sizeof(int32_t));- int32_t *nd = realloc(ddst, (size_t)nc * sizeof(int32_t));+ int32_t *ns = cbm_realloc(CBM_MEM_CLASS_OTHER, dsrc, (size_t)nc * sizeof(int32_t));+ int32_t *nd = cbm_realloc(CBM_MEM_CLASS_OTHER, ddst, (size_t)nc * sizeof(int32_t));if (!ns || !nd) {- free(ns ? ns : dsrc);- free(nd ? nd : ddst);+ cbm_free(CBM_MEM_CLASS_OTHER, ns ? ns : dsrc);+ cbm_free(CBM_MEM_CLASS_OTHER, nd ? nd : ddst);dsrc = ddst = NULL;dne = 0;break;@@ -433,11 +435,12 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const char}sqlite3_finalize(st);}- free(idmap);+ cbm_free(CBM_MEM_CLASS_OTHER, idmap);- g_flow_cache.data_first = malloc((size_t)n * sizeof(int32_t));- g_flow_cache.data_count = calloc((size_t)n, sizeof(int32_t));- g_flow_cache.data_edges = malloc(dne > 0 ? (size_t)dne * sizeof(int32_t) : sizeof(int32_t));+ g_flow_cache.data_first = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)n * sizeof(int32_t));+ g_flow_cache.data_count = cbm_atlas_calloc_array((size_t)n, sizeof(int32_t));+ g_flow_cache.data_edges =+ cbm_alloc(CBM_MEM_CLASS_OTHER, dne > 0 ? (size_t)dne * sizeof(int32_t) : sizeof(int32_t));if (g_flow_cache.data_first && g_flow_cache.data_count && g_flow_cache.data_edges) {for (int e = 0; e < dne; e++)g_flow_cache.data_count[dsrc[e]]++;@@ -446,23 +449,24 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const charg_flow_cache.data_first[i] = offset;offset += g_flow_cache.data_count[i];}- int32_t *cursor2 = calloc((size_t)n, sizeof(int32_t));+ int32_t *cursor2 = cbm_atlas_calloc_array((size_t)n, sizeof(int32_t));if (cursor2) {for (int e = 0; e < dne; e++)g_flow_cache.data_edges[g_flow_cache.data_first[dsrc[e]] + cursor2[dsrc[e]]++] =ddst[e];}- free(cursor2);+ cbm_free(CBM_MEM_CLASS_OTHER, cursor2);}- free(dsrc);- free(ddst);+ cbm_free(CBM_MEM_CLASS_OTHER, dsrc);+ cbm_free(CBM_MEM_CLASS_OTHER, ddst);for (int e = 0; e < ne; e++) {nodes[src[e]].out_count++;nodes[dst[e]].in_count++;}- int32_t *out_edges = malloc(ne > 0 ? (size_t)ne * sizeof(int32_t) : sizeof(int32_t));- int32_t *cursor = calloc((size_t)n, sizeof(int32_t));+ int32_t *out_edges =+ cbm_alloc(CBM_MEM_CLASS_OTHER, ne > 0 ? (size_t)ne * sizeof(int32_t) : sizeof(int32_t));+ int32_t *cursor = cbm_atlas_calloc_array((size_t)n, sizeof(int32_t));if (out_edges && cursor) {int32_t offset = 0;for (int i = 0; i < n; i++) {@@ -472,12 +476,13 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const charfor (int e = 0; e < ne; e++)out_edges[nodes[src[e]].first_out + cursor[src[e]]++] = dst[e];}- free(cursor);+ cbm_free(CBM_MEM_CLASS_OTHER, cursor);/* Reverse CSR over the same edge list (in_count already tallied). */- g_flow_cache.in_first = malloc((size_t)n * sizeof(int32_t));- g_flow_cache.in_edges = malloc(ne > 0 ? (size_t)ne * sizeof(int32_t) : sizeof(int32_t));- int32_t *rcursor = calloc((size_t)n, sizeof(int32_t));+ g_flow_cache.in_first = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)n * sizeof(int32_t));+ g_flow_cache.in_edges =+ cbm_alloc(CBM_MEM_CLASS_OTHER, ne > 0 ? (size_t)ne * sizeof(int32_t) : sizeof(int32_t));+ int32_t *rcursor = cbm_atlas_calloc_array((size_t)n, sizeof(int32_t));if (g_flow_cache.in_first && g_flow_cache.in_edges && rcursor) {int32_t offset = 0;for (int i = 0; i < n; i++) {@@ -487,22 +492,22 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const charfor (int e = 0; e < ne; e++)g_flow_cache.in_edges[g_flow_cache.in_first[dst[e]] + rcursor[dst[e]]++] = src[e];} else {- free(g_flow_cache.in_first);- free(g_flow_cache.in_edges);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.in_first);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.in_edges);g_flow_cache.in_first = NULL;g_flow_cache.in_edges = NULL;}- free(rcursor);- free(src);- free(dst);+ cbm_free(CBM_MEM_CLASS_OTHER, rcursor);+ cbm_free(CBM_MEM_CLASS_OTHER, src);+ cbm_free(CBM_MEM_CLASS_OTHER, dst);if (!out_edges) {for (int i = 0; i < n; i++) {- free(nodes[i].name);- free(nodes[i].file_path);+ cbm_free(CBM_MEM_CLASS_OTHER, nodes[i].name);+ cbm_free(CBM_MEM_CLASS_OTHER, nodes[i].file_path);}- free(nodes);- free(g_flow_cache.in_first);- free(g_flow_cache.in_edges);+ cbm_free(CBM_MEM_CLASS_OTHER, nodes);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.in_first);+ cbm_free(CBM_MEM_CLASS_OTHER, g_flow_cache.in_edges);g_flow_cache.in_first = NULL;g_flow_cache.in_edges = NULL;return -1;@@ -514,7 +519,7 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const charg_flow_cache.callable_total = n;/* 3. Score candidates, walk flows, dedup by (entry, terminal). */- fl_candidate_t *cands = malloc((size_t)n * sizeof(fl_candidate_t));+ fl_candidate_t *cands = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)n * sizeof(fl_candidate_t));if (!cands)return -1;int ncand = 0;@@ -527,9 +532,9 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const charint considered = ncand < FLOW_MAX_CANDIDATES ? ncand : FLOW_MAX_CANDIDATES;g_flow_cache.candidates_dropped = ncand - considered;- flow_t *flows = malloc(sizeof(flow_t) * FLOW_MAX_FLOWS * 2);+ flow_t *flows = cbm_alloc(CBM_MEM_CLASS_OTHER, sizeof(flow_t) * FLOW_MAX_FLOWS * 2);CBMHashTable *seen_pair = cbm_ht_create(256);- char **pair_keys = calloc(FLOW_MAX_FLOWS * 2, sizeof(char *));+ char **pair_keys = cbm_atlas_calloc_array(FLOW_MAX_FLOWS * 2, sizeof(char *));int nflows = 0;if (flows && seen_pair && pair_keys) {for (int c = 0; c < considered && nflows < FLOW_MAX_FLOWS * 2; c++) {@@ -564,10 +569,10 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const char}}for (int i = 0; i < FLOW_MAX_FLOWS * 2; i++)- free(pair_keys ? pair_keys[i] : NULL);- free(pair_keys);+ cbm_free(CBM_MEM_CLASS_OTHER, pair_keys ? pair_keys[i] : NULL);+ cbm_free(CBM_MEM_CLASS_OTHER, pair_keys);cbm_ht_free(seen_pair);- free(cands);+ cbm_free(CBM_MEM_CLASS_OTHER, cands);if (!flows)return -1;qsort(flows, (size_t)nflows, sizeof(flow_t), fl_flow_cmp);@@ -659,7 +664,7 @@ char *cbm_atlas_flows_json(cbm_store_t *store, const char *project) {}yyjson_mut_obj_add_val(doc, root, "flows", arr);pthread_mutex_unlock(&g_flow_mu);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -727,7 +732,7 @@ char *cbm_atlas_flow_json(cbm_store_t *store, const char *project, int flow_id)sqlite3_finalize(conf_st);yyjson_mut_obj_add_val(doc, root, "steps", steps);pthread_mutex_unlock(&g_flow_mu);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -793,16 +798,16 @@ char *cbm_atlas_trace_json(cbm_store_t *store, const char *project, int64_t fromfrom < 0 ? "source is not an indexed callable": "target is not an indexed callable");pthread_mutex_unlock(&g_flow_mu);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}/* BFS with parent tracking, bounded depth. */int n = g_flow_cache.node_count;- int32_t *parent = malloc((size_t)n * sizeof(int32_t));- uint8_t *depth = calloc((size_t)n, sizeof(uint8_t));- int32_t *queue = malloc((size_t)n * sizeof(int32_t));+ int32_t *parent = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)n * sizeof(int32_t));+ uint8_t *depth = cbm_atlas_calloc_array((size_t)n, sizeof(uint8_t));+ int32_t *queue = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)n * sizeof(int32_t));long long explored = 0;bool found = from == to;if (parent && depth && queue) {@@ -857,11 +862,11 @@ char *cbm_atlas_trace_json(cbm_store_t *store, const char *project, int64_t fromyyjson_mut_obj_add_val(doc, root, "path", path);yyjson_mut_obj_add_int(doc, root, "hops", chain_len - 1);}- free(parent);- free(depth);- free(queue);+ cbm_free(CBM_MEM_CLASS_OTHER, parent);+ cbm_free(CBM_MEM_CLASS_OTHER, depth);+ cbm_free(CBM_MEM_CLASS_OTHER, queue);pthread_mutex_unlock(&g_flow_mu);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -924,7 +929,7 @@ char *cbm_atlas_impact_json(cbm_store_t *store, const char *project, int64_t nodif (origin < 0) {yyjson_mut_obj_add_str(doc, root, "error", "symbol is not an indexed callable");pthread_mutex_unlock(&g_flow_mu);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -938,9 +943,9 @@ char *cbm_atlas_impact_json(cbm_store_t *store, const char *project, int64_t nodyyjson_mut_obj_add_strcpy(doc, node_obj, "file_path", nodes[origin].file_path);yyjson_mut_obj_add_val(doc, root, "node", node_obj);- uint8_t *dist = calloc((size_t)n, sizeof(uint8_t));- uint8_t *seen = calloc((size_t)n, sizeof(uint8_t));- int32_t *queue = malloc((size_t)n * sizeof(int32_t));+ uint8_t *dist = cbm_atlas_calloc_array((size_t)n, sizeof(uint8_t));+ uint8_t *seen = cbm_atlas_calloc_array((size_t)n, sizeof(uint8_t));+ int32_t *queue = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)n * sizeof(int32_t));yyjson_mut_val *nearest = yyjson_mut_arr(doc);yyjson_mut_val *tests_nearest = yyjson_mut_arr(doc);impact_region_t regions[IMPACT_REGIONS_CAP];@@ -1016,7 +1021,7 @@ char *cbm_atlas_impact_json(cbm_store_t *store, const char *project, int64_t nodrname = NULL;}}- free(rname);+ cbm_free(CBM_MEM_CLASS_OTHER, rname);cbm_ht_set(file_region, fp, (void *)(intptr_t)(ridx + 2));}}@@ -1067,13 +1072,13 @@ char *cbm_atlas_impact_json(cbm_store_t *store, const char *project, int64_t nodyyjson_mut_obj_add_val(doc, root, "tests", tests_obj);for (int r = 0; r < region_count; r++)- free(regions[r].name);+ cbm_free(CBM_MEM_CLASS_OTHER, regions[r].name);cbm_ht_free(file_region);- free(dist);- free(seen);- free(queue);+ cbm_free(CBM_MEM_CLASS_OTHER, dist);+ cbm_free(CBM_MEM_CLASS_OTHER, seen);+ cbm_free(CBM_MEM_CLASS_OTHER, queue);pthread_mutex_unlock(&g_flow_mu);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}diff --git a/src/ui/atlas_handout.c b/src/ui/atlas_handout.cindex 18a08eb22..2d01b65b6 100644--- a/src/ui/atlas_handout.c+++ b/src/ui/atlas_handout.c@@ -37,7 +37,7 @@ static void hd_put(hd_buf_t *b, const char *s) {size_t nc = b->cap ? b->cap * 2 : 16384;while (nc < b->len + n + 1)nc *= 2;- char *grown = realloc(b->data, nc);+ char *grown = cbm_realloc(CBM_MEM_CLASS_OTHER, b->data, nc);if (!grown) {b->oom = true;return;@@ -294,13 +294,13 @@ char *cbm_atlas_handout_html(cbm_store_t *store, const char *project) {yyjson_doc_free(flows_doc);if (bridges_doc)yyjson_doc_free(bridges_doc);- free(regions_json);- free(metrics_json);- free(flows_json);- free(bridges_json);+ cbm_free(CBM_MEM_CLASS_OTHER, regions_json);+ cbm_free(CBM_MEM_CLASS_OTHER, metrics_json);+ cbm_free(CBM_MEM_CLASS_OTHER, flows_json);+ cbm_free(CBM_MEM_CLASS_OTHER, bridges_json);if (b.oom) {- free(b.data);+ cbm_free(CBM_MEM_CLASS_OTHER, b.data);return NULL;}return b.data;diff --git a/src/ui/atlas_impact.c b/src/ui/atlas_impact.cindex c7518dc40..a6b12a4fe 100644--- a/src/ui/atlas_impact.c+++ b/src/ui/atlas_impact.c@@ -5,6 +5,7 @@#include "foundation/compat.h"#include "foundation/compat_thread.h"#include "foundation/constants.h"+#include "foundation/json_writer.h"#include "ui/atlas.h"#include "foundation/compat_fs.h"#include "foundation/subprocess.h"@@ -111,7 +112,7 @@ static void ia_structural(cbm_store_t *store, const char *project, const char *fyyjson_mut_obj_add_int(doc, out, "max_depth", IA_DEPTH);yyjson_mut_obj_add_int(doc, out, "visit_cap", IA_VISITS);yyjson_mut_obj_add_int(doc, out, "result_cap", IA_SHOWN);- ia_node_t *nodes = calloc(IA_VISITS, sizeof(*nodes));+ ia_node_t *nodes = cbm_atlas_calloc_array(IA_VISITS, sizeof(*nodes));sqlite3_stmt *st = NULL, *edges = NULL;int count = 0, seed_count = 0, visited_edges = 0, direct = 0, test_count = 0;bool capped = false, failed = false;@@ -208,7 +209,7 @@ finish:* evidence list is shortened. Tests remain visible among the first rows. */for (int i = seed_count; i < count && i < seed_count + IA_SHOWN; i++)yyjson_mut_arr_append(findings, ia_finding(doc, nodes, i));- free(nodes);+ cbm_free(CBM_MEM_CLASS_OTHER, nodes);}enum { IA_HASH = 64, IA_OUTPUT_CAP = 8 * 1024 * 1024 };@@ -276,23 +277,23 @@ static char *ia_git(const char *root, const char *const *args, size_t *size, timFILE *fp = cbm_fopen(log, "rb");if (!fp)goto cleanup;- output = malloc((size_t)length + 1);+ output = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)length + 1);if (output && fread(output, 1, (size_t)length, fp) == (size_t)length) {output[length] = '\0';*size = (size_t)length;} else {- free(output);+ cbm_free(CBM_MEM_CLASS_OTHER, output);output = NULL;}if (fclose(fp) != 0) {- free(output);+ cbm_free(CBM_MEM_CLASS_OTHER, output);output = NULL;*size = 0;}cleanup:cbm_subprocess_destroy(process);if (remove(log) != 0 && errno != ENOENT) {- free(output);+ cbm_free(CBM_MEM_CLASS_OTHER, output);output = NULL;*size = 0;}@@ -336,7 +337,7 @@ static void ia_history(const char *root_path, const char *file, yyjson_mut_doc *yyjson_mut_obj_add_str(doc, out, "meaning","Co-changes are historical association, not functional dependencies or ""defect probabilities.");- ia_cofile_t *cofiles = calloc(IA_COFILES, sizeof(*cofiles));+ ia_cofile_t *cofiles = cbm_atlas_calloc_array(IA_COFILES, sizeof(*cofiles));int scanned = 0, considered = 0, merges = 0, mass = 0, touching = 0, cocount = 0, errors = 0;bool available = false, truncated = false;char *raw = NULL;@@ -348,20 +349,20 @@ static void ia_history(const char *root_path, const char *file, yyjson_mut_doc *if (!cofiles || !head || !ia_hash(head)) {yyjson_mut_obj_add_str(doc, out, "error","No readable committed Git HEAD is available locally.");- free(head);+ cbm_free(CBM_MEM_CLASS_OTHER, head);goto finish;}yyjson_mut_obj_add_strcpy(doc, out, "head", head);char revision[IA_HASH + 1];snprintf(revision, sizeof(revision), "%s", head);- free(head);+ cbm_free(CBM_MEM_CLASS_OTHER, head);const char *shallow_args[] = {"rev-parse", "--is-shallow-repository", NULL};char *shallow = ia_git(root_path, shallow_args, &size, deadline, &truncated);if (shallow)yyjson_mut_obj_add_bool(doc, out, "shallow", strncmp(shallow, "true", 4) == 0);elseerrors++;- free(shallow);+ cbm_free(CBM_MEM_CLASS_OTHER, shallow);const char *status_args[] = {"--literal-pathspecs","status","--porcelain=v1",@@ -374,7 +375,7 @@ static void ia_history(const char *root_path, const char *file, yyjson_mut_doc *yyjson_mut_obj_add_bool(doc, out, "worktree_status_known", status != NULL);if (status)yyjson_mut_obj_add_bool(doc, out, "selection_uncommitted", size > 0);- free(status);+ cbm_free(CBM_MEM_CLASS_OTHER, status);const char *log_args[] = {"log","--max-count=201","--since=548.days",@@ -486,7 +487,7 @@ static void ia_history(const char *root_path, const char *file, yyjson_mut_doc *truncated = true;continue;}- cofiles[slot].file = strdup(other);+ cofiles[slot].file = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, other);if (!cofiles[slot].file) {errors++;continue;@@ -529,9 +530,9 @@ finish:yyjson_mut_obj_add_int(doc, out, "read_errors", errors);yyjson_mut_obj_add_int(doc, out, "cochanges_omitted", cocount > 15 ? cocount - 15 : 0);for (int i = 0; i < cocount; i++)- free(cofiles[i].file);- free(cofiles);- free(raw);+ cbm_free(CBM_MEM_CLASS_OTHER, cofiles[i].file);+ cbm_free(CBM_MEM_CLASS_OTHER, cofiles);+ cbm_free(CBM_MEM_CLASS_OTHER, raw);}char *cbm_atlas_impact_analysis_json(cbm_store_t *store, const char *project, const char *file,@@ -598,7 +599,7 @@ char *cbm_atlas_impact_analysis_json(cbm_store_t *store, const char *project, cosqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);ia_history(info.root_path ? info.root_path : "", file, doc, root, deadline);cbm_project_free_fields(&info);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -626,7 +627,11 @@ static void *ia_worker(void *unused) {pthread_mutex_lock(&ia_mu);ia_job.json =json ? json- : strdup("{\"status\":\"failed\",\"error\":\"Impact snapshot could not be read.\"}");+ : cbm_mem_strdup(+ CBM_MEM_CLASS_OTHER,+ "{\"status\":\"failed\",\"error\":\"Impact snapshot could not be read.\"}");+ /* Include fallback output before another thread can release the cache. */+ cbm_mem_class_flush_thread();ia_job.running = false;ia_job.completed = time(NULL);pthread_mutex_unlock(&ia_mu);@@ -636,19 +641,20 @@ static void *ia_worker(void *unused) {static void ia_clear_completed_locked(void) {if (ia_job.started)cbm_thread_join(&ia_job.thread);- free(ia_job.key);- free(ia_job.json);- free(ia_job.db_path);- free(ia_job.project);- free(ia_job.file);- free(ia_job.qn);+ cbm_free(CBM_MEM_CLASS_OTHER, ia_job.key);+ cbm_free(CBM_MEM_CLASS_OTHER, ia_job.json);+ cbm_free(CBM_MEM_CLASS_OTHER, ia_job.db_path);+ cbm_free(CBM_MEM_CLASS_OTHER, ia_job.project);+ cbm_free(CBM_MEM_CLASS_OTHER, ia_job.file);+ cbm_free(CBM_MEM_CLASS_OTHER, ia_job.qn);memset(&ia_job, 0, sizeof(ia_job));}char *cbm_atlas_impact_analysis_request(cbm_store_t *store, const char *project, const char *file,int64_t node_id, const char *qn, bool refresh) {if (!store || !project || !ia_path_valid(file))- return strdup(+ return cbm_mem_strdup(+ CBM_MEM_CLASS_OTHER,"{\"status\":\"failed\",\"error\":\"A relative indexed file path is required.\"}");char generation[80] = {0};cbm_store_generation(store, generation, sizeof(generation));@@ -658,11 +664,12 @@ char *cbm_atlas_impact_analysis_request(cbm_store_t *store, const char *project,const char *db_path = cbm_store_db_path(store);if (!db_path || !*db_path) {cbm_project_free_fields(&info);- return strdup("{\"status\":\"failed\",\"error\":\"Persistent index required.\"}");+ return cbm_mem_strdup(CBM_MEM_CLASS_OTHER,+ "{\"status\":\"failed\",\"error\":\"Persistent index required.\"}");}size_t key_size = strlen(db_path) + strlen(project) + strlen(file) + strlen(indexed_at) +(qn ? strlen(qn) : 0) + sizeof(generation) + 64;- char *key = malloc(key_size);+ char *key = cbm_alloc(CBM_MEM_CLASS_OTHER, key_size);if (!key) {cbm_project_free_fields(&info);return NULL;@@ -674,32 +681,34 @@ char *cbm_atlas_impact_analysis_request(cbm_store_t *store, const char *project,bool same = ia_job.key && strcmp(ia_job.key, key) == 0;if (ia_job.running) {pthread_mutex_unlock(&ia_mu);- free(key);- return strdup(same ? "{\"status\":\"pending\"}" : "{\"status\":\"busy\"}");+ cbm_free(CBM_MEM_CLASS_OTHER, key);+ return cbm_mem_strdup(CBM_MEM_CLASS_OTHER,+ same ? "{\"status\":\"pending\"}" : "{\"status\":\"busy\"}");}if (same && !refresh && time(NULL) - ia_job.completed < IA_CACHE_SECONDS) {- char *json = ia_job.json ? strdup(ia_job.json) : NULL;+ char *json = ia_job.json ? cbm_mem_strdup(CBM_MEM_CLASS_OTHER, ia_job.json) : NULL;pthread_mutex_unlock(&ia_mu);- free(key);+ cbm_free(CBM_MEM_CLASS_OTHER, key);return json;}ia_clear_completed_locked();ia_job.key = key;- ia_job.db_path = strdup(db_path);- ia_job.project = strdup(project);- ia_job.file = strdup(file);- ia_job.qn = strdup(qn ? qn : "");+ ia_job.db_path = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, db_path);+ ia_job.project = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, project);+ ia_job.file = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, file);+ ia_job.qn = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, qn ? qn : "");ia_job.node_id = node_id;ia_job.running = true;if (!ia_job.db_path || !ia_job.project || !ia_job.file || !ia_job.qn ||cbm_thread_create(&ia_job.thread, 0, ia_worker, NULL) != 0) {ia_clear_completed_locked();pthread_mutex_unlock(&ia_mu);- return strdup("{\"status\":\"failed\",\"error\":\"Analysis worker unavailable.\"}");+ return cbm_mem_strdup(CBM_MEM_CLASS_OTHER,+ "{\"status\":\"failed\",\"error\":\"Analysis worker unavailable.\"}");}ia_job.started = true;pthread_mutex_unlock(&ia_mu);- return strdup("{\"status\":\"pending\"}");+ return cbm_mem_strdup(CBM_MEM_CLASS_OTHER, "{\"status\":\"pending\"}");}void cbm_atlas_impact_analysis_shutdown(void) {diff --git a/src/ui/atlas_metrics.c b/src/ui/atlas_metrics.cindex 59fb395a7..45e493759 100644--- a/src/ui/atlas_metrics.c+++ b/src/ui/atlas_metrics.c@@ -12,6 +12,7 @@* cache dir, so the dashboard can show trends across reindexes.*/#include "foundation/constants.h"+#include "foundation/json_writer.h"#include "ui/atlas.h"#include "ui/http_server.h"#include "foundation/compat_fs.h"@@ -62,9 +63,9 @@ static void mx_top_offer2(mx_top_t *top, const char *qn, const char *name, constif (pos >= MX_TOP_N)return;mx_entry_t incoming;- incoming.qn = qn ? strdup(qn) : NULL;- incoming.name = name ? strdup(name) : NULL;- incoming.file = file ? strdup(file) : NULL;+ incoming.qn = qn ? cbm_mem_strdup(CBM_MEM_CLASS_OTHER, qn) : NULL;+ incoming.name = name ? cbm_mem_strdup(CBM_MEM_CLASS_OTHER, name) : NULL;+ incoming.file = file ? cbm_mem_strdup(CBM_MEM_CLASS_OTHER, file) : NULL;incoming.value = value;incoming.value2 = value2;mx_entry_t last = {0};@@ -76,9 +77,9 @@ static void mx_top_offer2(mx_top_t *top, const char *qn, const char *name, constfor (int i = top->count - 1; i > pos; i--)top->items[i] = top->items[i - 1];top->items[pos] = incoming;- free(last.qn);- free(last.name);- free(last.file);+ cbm_free(CBM_MEM_CLASS_OTHER, last.qn);+ cbm_free(CBM_MEM_CLASS_OTHER, last.name);+ cbm_free(CBM_MEM_CLASS_OTHER, last.file);}static void mx_top_offer(mx_top_t *top, const char *qn, const char *name, const char *file,@@ -88,9 +89,9 @@ static void mx_top_offer(mx_top_t *top, const char *qn, const char *name, conststatic void mx_top_free(mx_top_t *top) {for (int i = 0; i < top->count; i++) {- free(top->items[i].qn);- free(top->items[i].name);- free(top->items[i].file);+ cbm_free(CBM_MEM_CLASS_OTHER, top->items[i].qn);+ cbm_free(CBM_MEM_CLASS_OTHER, top->items[i].name);+ cbm_free(CBM_MEM_CLASS_OTHER, top->items[i].file);}top->count = 0;}@@ -126,7 +127,7 @@ static pthread_mutex_t g_mx_mu = PTHREAD_MUTEX_INITIALIZER;void cbm_atlas_metrics_cache_clear(void) {pthread_mutex_lock(&g_mx_mu);- free(g_mx_cache.json);+ cbm_free(CBM_MEM_CLASS_OTHER, g_mx_cache.json);memset(&g_mx_cache, 0, sizeof(g_mx_cache));pthread_mutex_unlock(&g_mx_mu);}@@ -203,7 +204,7 @@ static void mx_churn_scan(const char *root_path, mx_churn_t *churn) {FILE *fp = cbm_popen_git(cmd);if (!fp)return;- churn->commits = malloc((size_t)MX_COMMIT_CAP * sizeof(mx_commit_t));+ churn->commits = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)MX_COMMIT_CAP * sizeof(mx_commit_t));int current_commit = -1;char line[CBM_SZ_1K];while (fgets(line, sizeof(line), fp)) {@@ -251,16 +252,17 @@ static void mx_churn_scan(const char *root_path, mx_churn_t *churn) {if (!stat) {if (churn->key_count >= churn->key_cap) {int nc = churn->key_cap ? churn->key_cap * 2 : 1024;- char **grown = realloc(churn->keys, (size_t)nc * sizeof(char *));+ char **grown =+ cbm_realloc(CBM_MEM_CLASS_OTHER, churn->keys, (size_t)nc * sizeof(char *));if (!grown)break;churn->keys = grown;churn->key_cap = nc;}- churn->keys[churn->key_count] = strdup(line);- stat = calloc(1, sizeof(mx_file_stat_t));+ churn->keys[churn->key_count] = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, line);+ stat = cbm_atlas_calloc_array(1, sizeof(mx_file_stat_t));if (!churn->keys[churn->key_count] || !stat) {- free(stat);+ cbm_free(CBM_MEM_CLASS_OTHER, stat);break;}canon = churn->keys[churn->key_count];@@ -289,7 +291,7 @@ static void mx_churn_free_stat(const char *key, void *value, void *userdata) {mx_file_stat_t *stat = value;if (stat) {cbm_ht_free(stat->authors);- free(stat);+ cbm_free(CBM_MEM_CLASS_OTHER, stat);}}@@ -298,9 +300,9 @@ static void mx_churn_free(mx_churn_t *churn) {cbm_ht_foreach(churn->counts, mx_churn_free_stat, NULL);cbm_ht_free(churn->counts);for (int i = 0; i < churn->key_count; i++)- free(churn->keys[i]);- free(churn->keys);- free(churn->commits);+ cbm_free(CBM_MEM_CLASS_OTHER, churn->keys[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, churn->keys);+ cbm_free(CBM_MEM_CLASS_OTHER, churn->commits);memset(churn, 0, sizeof(*churn));}@@ -331,11 +333,11 @@ static void mx_history_append_and_emit(yyjson_mut_doc *doc, yyjson_mut_val *rootif (strstr(buf, stamp))stamp_present = true;if (line_count == MX_HISTORY_MAX) {- free(lines[0]);+ cbm_free(CBM_MEM_CLASS_OTHER, lines[0]);memmove(lines, lines + 1, (size_t)(MX_HISTORY_MAX - 1) * sizeof(char *));line_count--;}- lines[line_count] = strdup(buf);+ lines[line_count] = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, buf);if (!lines[line_count])break;line_count++;@@ -365,7 +367,7 @@ static void mx_history_append_and_emit(yyjson_mut_doc *doc, yyjson_mut_val *rootyyjson_mut_arr_append(history, copy);yyjson_doc_free(entry);}- free(lines[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, lines[i]);}yyjson_mut_obj_add_val(doc, root, "history", history);}@@ -439,14 +441,15 @@ static char *mx_build_json(cbm_store_t *store, const char *project, const char *if (!canon) {if (file_key_count >= file_key_cap) {int nc = file_key_cap ? file_key_cap * 2 : 1024;- char **grown = realloc(file_keys, (size_t)nc * sizeof(char *));+ char **grown = cbm_realloc(CBM_MEM_CLASS_OTHER, file_keys,+ (size_t)nc * sizeof(char *));if (grown) {file_keys = grown;file_key_cap = nc;}}if (file_key_count < file_key_cap) {- file_keys[file_key_count] = strdup(file);+ file_keys[file_key_count] = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, file);if (file_keys[file_key_count]) {canon = file_keys[file_key_count];file_key_count++;@@ -614,10 +617,10 @@ static char *mx_build_json(cbm_store_t *store, const char *project, const char *mx_history_cache_store(project, stamp, &churn); /* takes ownership */cbm_ht_free(file_cplx);for (int i = 0; i < file_key_count; i++)- free(file_keys[i]);- free(file_keys);+ cbm_free(CBM_MEM_CLASS_OTHER, file_keys[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, file_keys);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -679,7 +682,7 @@ char *cbm_atlas_file_history_json(cbm_store_t *store, const char *project, constif (!fresh) {/* The metrics build populates the cache; run it if needed. */char *metrics = cbm_atlas_metrics_json(store, project);- free(metrics);+ cbm_free(CBM_MEM_CLASS_OTHER, metrics);}yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);@@ -730,7 +733,7 @@ char *cbm_atlas_file_history_json(cbm_store_t *store, const char *project, const}pthread_mutex_unlock(&g_hist_mu);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -745,7 +748,7 @@ char *cbm_atlas_metrics_json(cbm_store_t *store, const char *project) {snprintf(key, sizeof(key), "%s|%s", project, stamp);pthread_mutex_lock(&g_mx_mu);if (g_mx_cache.json && strcmp(g_mx_cache.key, key) == 0) {- char *copy = strdup(g_mx_cache.json);+ char *copy = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, g_mx_cache.json);pthread_mutex_unlock(&g_mx_mu);return copy;}@@ -755,8 +758,8 @@ char *cbm_atlas_metrics_json(cbm_store_t *store, const char *project) {if (!json)return NULL;pthread_mutex_lock(&g_mx_mu);- free(g_mx_cache.json);- g_mx_cache.json = strdup(json);+ cbm_free(CBM_MEM_CLASS_OTHER, g_mx_cache.json);+ g_mx_cache.json = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, json);snprintf(g_mx_cache.key, sizeof(g_mx_cache.key), "%s", key);pthread_mutex_unlock(&g_mx_mu);return json;@@ -832,7 +835,7 @@ char *cbm_atlas_who_json(cbm_store_t *store, const char *project, const char *fipthread_mutex_unlock(&g_hist_mu);if (!fresh) {char *metrics = cbm_atlas_metrics_json(store, project);- free(metrics);+ cbm_free(CBM_MEM_CLASS_OTHER, metrics);}yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);@@ -884,7 +887,7 @@ char *cbm_atlas_who_json(cbm_store_t *store, const char *project, const char *fi}pthread_mutex_unlock(&g_hist_mu);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -928,7 +931,7 @@ static void mx_remote_url(const char *root_path, char *out, size_t cap) {if (!https)return;snprintf(out, cap, "%s", https);- free(https);+ cbm_free(CBM_MEM_CLASS_OTHER, https);}char *cbm_atlas_symbol_history_json(cbm_store_t *store, const char *project, const char *file_path,@@ -951,7 +954,7 @@ char *cbm_atlas_symbol_history_json(cbm_store_t *store, const char *project, conif (!root_path[0] || !cbm_validate_shell_path_arg(root_path) ||!cbm_validate_shell_path_arg(file_path) || strstr(file_path, "..")) {yyjson_mut_obj_add_bool(doc, root, "available", false);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -976,7 +979,7 @@ char *cbm_atlas_symbol_history_json(cbm_store_t *store, const char *project, conFILE *fp = cbm_popen_git(cmd);if (!fp) {yyjson_mut_obj_add_bool(doc, root, "available", false);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -1020,7 +1023,7 @@ char *cbm_atlas_symbol_history_json(cbm_store_t *store, const char *project, conyyjson_mut_obj_add_bool(doc, root, "available", status == 0 || count > 0);yyjson_mut_obj_add_val(doc, root, "commits", commits);yyjson_mut_obj_add_bool(doc, root, "truncated", count >= 12);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}diff --git a/src/ui/atlas_repository.c b/src/ui/atlas_repository.cindex 92bfc5338..0c0805475 100644--- a/src/ui/atlas_repository.c+++ b/src/ui/atlas_repository.c@@ -1,5 +1,6 @@/* Semantic repository map, independent of the rendering/layout node budget. */#include "ui/atlas.h"+#include "foundation/json_writer.h"#include <sqlite3.h>#include <yyjson/yyjson.h>#include <math.h>@@ -139,7 +140,7 @@ char *cbm_atlas_repository_json(cbm_store_t *store, const char *project) {"recorded relation types between retained semantic nodes; other endpoints omitted");if (sqlite3_exec(db, "COMMIT", NULL, NULL, NULL) != SQLITE_OK)goto fail;- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;fail:diff --git a/src/ui/atlas_why.c b/src/ui/atlas_why.cindex 0d26bfc75..56754434c 100644--- a/src/ui/atlas_why.c+++ b/src/ui/atlas_why.c@@ -12,6 +12,7 @@#include "foundation/compat_fs.h"#include "foundation/constants.h"+#include "foundation/json_writer.h"#include "ui/atlas.h"#include "cbm.h"@@ -59,7 +60,7 @@ static why_file_t *why_file_get(why_cache_t *cache, const char *file_path) {if (cache->count >= WHY_MAX_FILES)return NULL;why_file_t *slot = &cache->files[cache->count++];- slot->file_path = strdup(file_path);+ slot->file_path = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, file_path);if (!slot->file_path)return NULL;@@ -75,7 +76,7 @@ static why_file_t *why_file_get(why_cache_t *cache, const char *file_path) {fclose(fp);return NULL;}- char *source = malloc((size_t)size + 1);+ char *source = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)size + 1);if (!source) {fclose(fp);return NULL;@@ -87,7 +88,7 @@ static why_file_t *why_file_get(why_cache_t *cache, const char *file_path) {const char *dot = strrchr(file_path, '.');CBMLanguage lang = cbm_language_for_extension(dot ? dot : "");if (lang == CBM_LANG_COUNT) {- free(source);+ cbm_free(CBM_MEM_CLASS_OTHER, source);return NULL;}CBMFileResult *result = cbm_extract_file(source, (int)got, lang, cache->project, file_path,@@ -95,7 +96,7 @@ static why_file_t *why_file_get(why_cache_t *cache, const char *file_path) {if (!result || !result->cached_tree) {if (result)cbm_free_result(result);- free(source);+ cbm_free(CBM_MEM_CLASS_OTHER, source);return NULL;}slot->source = source;@@ -106,8 +107,8 @@ static why_file_t *why_file_get(why_cache_t *cache, const char *file_path) {static void why_cache_free(why_cache_t *cache) {for (int i = 0; i < cache->count; i++) {- free(cache->files[i].file_path);- free(cache->files[i].source);+ cbm_free(CBM_MEM_CLASS_OTHER, cache->files[i].file_path);+ cbm_free(CBM_MEM_CLASS_OTHER, cache->files[i].source);if (cache->files[i].result)cbm_free_result(cache->files[i].result);}@@ -434,7 +435,7 @@ char *cbm_atlas_why_json(cbm_store_t *store, const char *project, int64_t node_iyyjson_mut_obj_add_bool(doc, jroot, "sources_readable", have_root);why_cache_free(&cache);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -464,7 +465,7 @@ char *cbm_atlas_callsite_guards_json(cbm_store_t *store, const char *project, coyyjson_mut_doc_free(doc);return NULL;}- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}diff --git a/src/ui/http_server.c b/src/ui/http_server.cindex d67908db6..1523f71fa 100644--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@ -34,6 +34,7 @@/* pipeline.h no longer needed — indexing runs as subprocess */#include "foundation/log.h"#include "foundation/mem_core.h"+#include "foundation/json_writer.h"#include "foundation/platform.h"#include "foundation/secure_random.h"#include "foundation/sha256.h"@@ -283,8 +284,8 @@ char *cbm_ui_git_strip_credentials(const char *url) {/* Normalize a git remote URL (scp-style, ssh://, https://) to a canonical* "https://host/org/repo" web base with any trailing ".git" and any embedded- * credentials removed. Returns a malloc'd string or NULL if the shape isn't- * recognized. Caller frees. */+ * credentials removed. Returns an OTHER-owned string or NULL if the shape isn't+ * recognized. Release with cbm_free(CBM_MEM_CLASS_OTHER, result). */char *cbm_ui_git_web_base(const char *url) {if (!url || !url[0])return NULL;@@ -312,7 +313,7 @@ char *cbm_ui_git_web_base(const char *url) {if (l > 0 && host_path[l - 1] == '/')host_path[l - 1] = '\0';size_t out_sz = strlen(host_path) + 9; /* "https://" (8) + NUL */- char *out = malloc(out_sz);+ char *out = cbm_alloc(CBM_MEM_CLASS_OTHER, out_sz);if (!out)return NULL;/* Legitimate GitHub blob-URL construction, not a network call — the scheme@@ -415,7 +416,7 @@ static void handle_repo_info(cbm_http_conn_t *c, const cbm_http_req_t *req) {free(remote);free(remote_safe);- free(web_base);+ cbm_free(CBM_MEM_CLASS_OTHER, web_base);}/* ── Log ring buffer ──────────────────────────────────────────── */@@ -588,7 +589,7 @@ static void handle_logs(cbm_http_conn_t *c, const cbm_http_req_t *req) {cbm_mutex_unlock(&g_log_mutex);if (persistent) {cbm_http_replyf(c, 200, g_cors_json, "%s", persistent);- free(persistent);+ cbm_free(CBM_MEM_CLASS_OTHER, persistent);return;}/* The legacy memory ring has no trustworthy project provenance. Never@@ -688,7 +689,7 @@ static void handle_agent_events(cbm_http_conn_t *c, const cbm_http_req_t *req, bjson ? json: status == 400 ? "{\"error\":\"invalid event batch\"}": "{\"error\":\"activity storage unavailable\"}");- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);}/* ── Frontend log file ────────────────────────────────────────── */@@ -758,10 +759,10 @@ static bool ui_log_import_legacy(sqlite3 *db, const char *cache) {break;}size_t length = size > UI_LOG_TAIL_READ_BYTES ? UI_LOG_TAIL_READ_BYTES : (size_t)size;- char *data = malloc(length + 1);+ char *data = cbm_alloc(CBM_MEM_CLASS_OTHER, length + 1);if (!data || (size > (int64_t)length &&fseek(file, (long)(size - (int64_t)length), SEEK_SET) != 0)) {- free(data);+ cbm_free(CBM_MEM_CLASS_OTHER, data);fclose(file);ok = false;break;@@ -794,7 +795,7 @@ static bool ui_log_import_legacy(sqlite3 *db, const char *cache) {yyjson_doc_free(record);line = end + 1;}- free(data);+ cbm_free(CBM_MEM_CLASS_OTHER, data);}if (ok)ok = sqlite3_exec(db,@@ -896,10 +897,10 @@ static void handle_ui_log_post(cbm_http_conn_t *c, const cbm_http_req_t *req) {return;}- ui_log_scratch_t *s = calloc(1, sizeof(*s));+ ui_log_scratch_t *s = cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*s));char path[CBM_SZ_1K];if (!s || !cbm_ui_log_file_path(path, sizeof(path))) {- free(s);+ cbm_free(CBM_MEM_CLASS_OTHER, s);yyjson_doc_free(doc);cbm_http_replyf(c, 500, g_cors_json, "{\"error\":\"no log path\"}");return;@@ -929,7 +930,7 @@ static void handle_ui_log_post(cbm_http_conn_t *c, const cbm_http_req_t *req) {sqlite3 *db = activity_db_locked();if (!db) {cbm_mutex_unlock(&g_log_mutex);- free(s);+ cbm_free(CBM_MEM_CLASS_OTHER, s);yyjson_doc_free(doc);cbm_http_replyf(c, 503, g_cors_json, "{\"error\":\"activity storage unavailable\"}");return;@@ -1027,7 +1028,7 @@ static void handle_ui_log_post(cbm_http_conn_t *c, const cbm_http_req_t *req) {"\"persistent\":true,\"storage_error\":%s,\"file_error\":%s}",accepted, dropped, duplicates, s->esc, storage_error ? "true" : "false",file_error ? "true" : "false");- free(s);+ cbm_free(CBM_MEM_CLASS_OTHER, s);yyjson_doc_free(doc);}@@ -1055,7 +1056,7 @@ static void handle_ui_log_get(cbm_http_conn_t *c, const cbm_http_req_t *req) {cbm_mutex_unlock(&g_log_mutex);cbm_http_replyf(c, json ? 200 : 503, g_cors_json, "%s",json ? json : "{\"error\":\"activity storage unavailable\"}");- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);}/* ── Process monitoring ───────────────────────────────────────── */@@ -1223,7 +1224,6 @@ static void handle_processes(cbm_http_conn_t *c) {/* ── Directory browser ────────────────────────────────────────── */-static void append_roots_json(char *buf, size_t bufsz, int *pos) {http_appendf(buf, bufsz, pos, ",\"roots\":[");#ifdef _WIN32@@ -1899,7 +1899,7 @@ static void handle_project_health(cbm_http_conn_t *c, const cbm_http_req_t *req,char db_path[1024];db_path_for_project(name, db_path, sizeof(db_path));- yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_doc *doc = yyjson_mut_doc_new(cbm_json_writer_allocator());yyjson_mut_val *root = doc ? yyjson_mut_obj(doc) : NULL;if (!doc || !root) {yyjson_mut_doc_free(doc);@@ -1936,11 +1936,11 @@ static void handle_project_health(cbm_http_conn_t *c, const cbm_http_req_t *req,}cbm_project_free_fields(&project);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);if (json) {cbm_http_replyf(c, 200, g_cors_json, "%s", json);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);} else {cbm_http_replyf(c, 500, g_cors_json, "{\"error\":\"out of memory\"}");}@@ -2123,7 +2123,7 @@ static void handle_layout(cbm_http_conn_t *c, const cbm_http_req_t *req) {return;}cbm_http_replyf(c, 200, g_cors_json, "%s", regions_json);- free(regions_json);+ cbm_free(CBM_MEM_CLASS_OTHER, regions_json);return;}@@ -2397,7 +2397,7 @@ static void atlas_reply_json(cbm_http_conn_t *c, char *json, int missing_status,return;}cbm_http_replyf(c, 200, g_cors_json, "%s", json);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);}/* GET /api/tree?project=X&path=src/foo — Modules aggregates. */@@ -2460,7 +2460,7 @@ static void handle_atlas_repository(cbm_http_conn_t *c, const cbm_http_req_t *reif (length > 1024 * 1024)cbm_http_conn_set_send_deadline_ms(c, 5000);cbm_http_reply_buf(c, 200, g_cors_json, json, length);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);}static void handle_atlas_impact_analysis(cbm_http_conn_t *c, const cbm_http_req_t *req) {@@ -2503,7 +2503,7 @@ static char *atlas_trace_attach_guards(cbm_store_t *store, const char *project,yyjson_doc_free(doc);return json;}- yyjson_mut_doc *mut = yyjson_doc_mut_copy(doc, NULL);+ yyjson_mut_doc *mut = yyjson_doc_mut_copy(doc, cbm_json_writer_allocator());yyjson_doc_free(doc);if (!mut)return json;@@ -2544,7 +2544,7 @@ static char *atlas_trace_attach_guards(cbm_store_t *store, const char *project,if (!gj)continue;yyjson_doc *gd = yyjson_read(gj, strlen(gj), 0);- free(gj);+ cbm_free(CBM_MEM_CLASS_OTHER, gj);if (!gd)continue;yyjson_val *garr = yyjson_obj_get(yyjson_doc_get_root(gd), "guards");@@ -2555,11 +2555,11 @@ static char *atlas_trace_attach_guards(cbm_store_t *store, const char *project,}yyjson_doc_free(gd);}- char *out = yyjson_mut_write(mut, 0, NULL);+ char *out = yyjson_mut_write_opts(mut, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(mut);if (!out)return json;- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);return out;}@@ -2611,7 +2611,7 @@ char *cbm_atlas_attach_observed(cbm_store_t *store, const char *project, char *jyyjson_doc_free(doc);return json;}- yyjson_mut_doc *mut = yyjson_doc_mut_copy(doc, NULL);+ yyjson_mut_doc *mut = yyjson_doc_mut_copy(doc, cbm_json_writer_allocator());yyjson_doc_free(doc);if (!mut)return json;@@ -2680,11 +2680,11 @@ char *cbm_atlas_attach_observed(cbm_store_t *store, const char *project, char *j}sqlite3_finalize(qn_stmt);}- char *out = yyjson_mut_write(mut, 0, NULL);+ char *out = yyjson_mut_write_opts(mut, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(mut);if (!out)return json;- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);return out;}@@ -2766,7 +2766,7 @@ static char *atlas_flow_attach_guards(cbm_store_t *store, const char *project, cyyjson_doc_free(doc);return json;}- yyjson_mut_doc *mut = yyjson_doc_mut_copy(doc, NULL);+ yyjson_mut_doc *mut = yyjson_doc_mut_copy(doc, cbm_json_writer_allocator());yyjson_doc_free(doc);if (!mut)return json;@@ -2810,7 +2810,7 @@ static char *atlas_flow_attach_guards(cbm_store_t *store, const char *project, cif (!gj)continue;yyjson_doc *gd = yyjson_read(gj, strlen(gj), 0);- free(gj);+ cbm_free(CBM_MEM_CLASS_OTHER, gj);if (!gd)continue;yyjson_val *garr = yyjson_obj_get(yyjson_doc_get_root(gd), "guards");@@ -2821,11 +2821,11 @@ static char *atlas_flow_attach_guards(cbm_store_t *store, const char *project, c}yyjson_doc_free(gd);}- char *out = yyjson_mut_write(mut, 0, NULL);+ char *out = yyjson_mut_write_opts(mut, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(mut);if (!out)return json;- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);return out;}@@ -2866,7 +2866,7 @@ static void handle_atlas_handout(cbm_http_conn_t *c, const cbm_http_req_t *req)return;}cbm_http_replyf(c, 200, g_cors_html, "%s", html);- free(html);+ cbm_free(CBM_MEM_CLASS_OTHER, html);}/* GET /api/blast?project=X&files=a,b,c — bucket a file list by region. */@@ -3201,15 +3201,15 @@ static void dispatch_request(cbm_http_server_t *srv, cbm_http_conn_t *c,cbm_runtime_settings_note_http_port(srv->port);const char *cache = cbm_resolve_cache_dir();int status = 200;- char *json = is_post ? cbm_runtime_settings_apply_json(cache, req->body, req->body_len, &status)- : cbm_runtime_settings_get_json(cache);+ char *json = is_post+ ? cbm_runtime_settings_apply_json(cache, req->body, req->body_len, &status)+ : cbm_runtime_settings_get_json(cache);if (!json) {status = 500;}- cbm_http_replyf(c, status,- "Content-Type: application/json\r\nCache-Control: no-store\r\n",+ cbm_http_replyf(c, status, "Content-Type: application/json\r\nCache-Control: no-store\r\n","%s", json ? json : "{\"error\":\"Configuration storage unavailable.\"}");- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);return;}@@ -3553,6 +3553,7 @@ void cbm_http_server_run(cbm_http_server_t *srv) {memory_order_acq_rel, memory_order_acquire))return;if (!srv->listener_ok) {+ cbm_mem_class_flush_thread();atomic_store_explicit(&srv->run_state, HTTP_RUN_COMPLETED, memory_order_release);return;}@@ -3585,7 +3586,10 @@ void cbm_http_server_run(cbm_http_server_t *srv) {cbm_http_conn_response_bytes(conn));}cbm_httpd_conn_close(conn);+ /* Retained response caches can be released by a different thread. */+ cbm_mem_class_flush_thread();}+ cbm_mem_class_flush_thread();atomic_store_explicit(&srv->run_state, HTTP_RUN_COMPLETED, memory_order_release);}diff --git a/src/ui/http_server.h b/src/ui/http_server.hindex cf4272585..b42326157 100644--- a/src/ui/http_server.h+++ b/src/ui/http_server.h@@ -119,7 +119,8 @@ bool cbm_http_server_resolve_binary_path(const char *argv0, char *out, size_t ou/* Normalize a git remote (scp-style / ssh:// / https://) to a canonical* "https://host/org/repo" web base, with trailing ".git" and any embedded- * credentials removed. malloc'd or NULL. Caller frees. */+ * credentials removed. OTHER-owned or NULL; release with+ * cbm_free(CBM_MEM_CLASS_OTHER, result). */char *cbm_ui_git_web_base(const char *url);/* Copy `url` with any "user[:password]@" userinfo stripped from adiff --git a/src/ui/layout3d.c b/src/ui/layout3d.cindex 9431d1bae..eebed1893 100644--- a/src/ui/layout3d.c+++ b/src/ui/layout3d.c@@ -14,6 +14,7 @@#include "ui/layout3d.h"#include "ui/layout_internal.h"#include "foundation/log.h"+#include "foundation/mem_core.h"#include "foundation/platform.h"#include <yyjson/yyjson.h>@@ -523,15 +524,15 @@ cbm_layout_result_t *cbm_layout_compute(cbm_store_t *store, const char *project,cbm_search_output_t search_out;memset(&search_out, 0, sizeof(search_out));if (cbm_store_search(store, ¶ms, &search_out) != CBM_STORE_OK)- return calloc(CBM_ALLOC_ONE, sizeof(cbm_layout_result_t));+ return cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(cbm_layout_result_t));int n = search_out.count, total_count = search_out.total;cbm_node_t *node_arr = NULL;if (n > 0) {- node_arr = malloc((size_t)n * sizeof(cbm_node_t));+ node_arr = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)n * sizeof(cbm_node_t));if (!node_arr) {cbm_store_search_free(&search_out);- cbm_layout_result_t *r = calloc(CBM_ALLOC_ONE, sizeof(*r));+ cbm_layout_result_t *r = cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*r));if (r)r->total_nodes = total_count;return r;@@ -540,7 +541,7 @@ cbm_layout_result_t *cbm_layout_compute(cbm_store_t *store, const char *project,node_arr[i] = search_out.results[i].node;}cbm_layout_result_t *result = cbm_layout_from_nodes(store, project, node_arr, n, total_count);- free(node_arr);+ cbm_free(CBM_MEM_CLASS_OTHER, node_arr);cbm_store_search_free(&search_out);return result;}@@ -548,10 +549,10 @@ cbm_layout_result_t *cbm_layout_compute(cbm_store_t *store, const char *project,cbm_layout_result_t *cbm_layout_from_nodes(cbm_store_t *store, const char *project,const cbm_node_t *nodes, int n, int total_nodes) {int total_count = total_nodes;- if (!store || !project || n < 0)+ if (!store || !project || n < 0 || (size_t)n > SIZE_MAX / sizeof(int))return NULL;if (n == 0 || !nodes) {- cbm_layout_result_t *r = calloc(CBM_ALLOC_ONE, sizeof(*r));+ cbm_layout_result_t *r = cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*r));if (r)r->total_nodes = total_count;return r;@@ -560,7 +561,7 @@ cbm_layout_result_t *cbm_layout_from_nodes(cbm_store_t *store, const char *proje/* 2. Build sorted node-ID → index map for O(log n) edge filtering */node_id_entry_t *id_map = malloc((size_t)n * sizeof(node_id_entry_t));if (!id_map) {- cbm_layout_result_t *r = calloc(CBM_ALLOC_ONE, sizeof(*r));+ cbm_layout_result_t *r = cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*r));if (r) {r->total_nodes = total_count;}@@ -646,7 +647,7 @@ cbm_layout_result_t *cbm_layout_from_nodes(cbm_store_t *store, const char *proje/* 5. Seed positions: ring by directory cluster key + z from call depth */cbm_layout_body_t *bodies = calloc((size_t)n, sizeof(cbm_layout_body_t));- cbm_layout_result_t *result = calloc(CBM_ALLOC_ONE, sizeof(*result));+ cbm_layout_result_t *result = cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*result));if (!result || !bodies) {free(bodies);free(deg);@@ -668,7 +669,7 @@ cbm_layout_result_t *cbm_layout_from_nodes(cbm_store_t *store, const char *proje* having zero callers. */int64_t *node_ids = malloc((size_t)n * sizeof(int64_t));int *in_calls = calloc((size_t)n, sizeof(int));- int *out_calls = calloc((size_t)n, sizeof(int));+ int *out_calls = cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)n * sizeof(int));int *in_usage = calloc((size_t)n, sizeof(int));int *in_call_reference = calloc((size_t)n, sizeof(int));int *deg_dummy = calloc((size_t)n, sizeof(int));@@ -799,7 +800,7 @@ cbm_layout_result_t *cbm_layout_from_nodes(cbm_store_t *store, const char *projefree(cdepth);free(node_ids);free(in_calls);- free(out_calls);+ cbm_free(CBM_MEM_CLASS_OTHER, out_calls);free(in_usage);free(in_call_reference);free(deg_dummy);@@ -820,7 +821,7 @@ void cbm_layout_free(cbm_layout_result_t *r) {for (int i = 0; i < r->edge_count; i++)free((void *)r->edges[i].type);free(r->edges);- free(r);+ cbm_free(CBM_MEM_CLASS_OTHER, r);}char *cbm_layout_to_json(const cbm_layout_result_t *r) {diff --git a/src/ui/layout3d.h b/src/ui/layout3d.hindex 44d71aa0c..0a3d65770 100644--- a/src/ui/layout3d.h+++ b/src/ui/layout3d.h@@ -66,7 +66,7 @@ cbm_layout_result_t *cbm_layout_compute(cbm_store_t *store, const char *project,cbm_layout_level_t level, const char *center_node,int radius, int max_nodes);-/* Free a layout result. */+/* Release a computed layout result and its fields through their matching allocators. */void cbm_layout_free(cbm_layout_result_t *result);/* Serialize layout result to JSON string. Caller must free(). */@@ -77,7 +77,8 @@ char *cbm_layout_to_json(const cbm_layout_result_t *result);/* level=regions payload: one body per region (Leiden communities voted per* file, folder groups as fallback), aggregated region→region edge weights,* deterministic positions. Cached per (project, indexed_at). Returns a- * heap-allocated JSON document; caller frees. NULL on error. */+ * OTHER-owned JSON document; release with cbm_free(CBM_MEM_CLASS_OTHER, result).+ * NULL on error. */char *cbm_layout_regions_json(cbm_store_t *store, const char *project);/* scope=region:<id> — full-detail layout restricted to one region's files.diff --git a/src/ui/layout_internal.h b/src/ui/layout_internal.hindex ddd36d127..19c11d055 100644--- a/src/ui/layout_internal.h+++ b/src/ui/layout_internal.h@@ -34,7 +34,8 @@ uint32_t cbm_layout_fnv1a(const char *s);float cbm_layout_rand_float(uint32_t *seed);/* Layout core: seed + optimize + classify an explicit node array. Borrowed- * `nodes` structs (strings are copied into the result). `total_nodes` is the+ * `nodes` structs and strings remain owned by the caller; the result copies+ * them and is released with cbm_layout_free. `total_nodes` is the* project-wide count the caller knows (may exceed n). */cbm_layout_result_t *cbm_layout_from_nodes(cbm_store_t *store, const char *project,const cbm_node_t *nodes, int n, int total_nodes);diff --git a/src/ui/layout_regions.c b/src/ui/layout_regions.cindex 0358581bc..0b02643b0 100644--- a/src/ui/layout_regions.c+++ b/src/ui/layout_regions.c@@ -18,7 +18,9 @@* scopes reuse one computation.*/#include "foundation/constants.h"+#include "foundation/json_writer.h"#include "ui/layout_internal.h"+#include "ui/atlas.h"#include "foundation/hash_table.h"#include "foundation/log.h"@@ -69,26 +71,26 @@ typedef struct {typedef struct {char key[1152];- char *json; /* serialized regions payload */+ char *json; /* serialized regions payload */int region_count;- char ***region_files; /* per region: owned file_path strings */+ char ***region_files; /* per region: owned file_path strings */int *region_file_count;long long total_nodes;- CBMHashTable *file_ht; /* file_path (borrowed from region_files) → region+1 */+ CBMHashTable *file_ht; /* file_path (borrowed from region_files) → region+1 */} region_cache_t;static region_cache_t g_region_cache;static pthread_mutex_t g_region_mu = PTHREAD_MUTEX_INITIALIZER;static void region_cache_clear_locked(void) {- free(g_region_cache.json);+ cbm_free(CBM_MEM_CLASS_OTHER, g_region_cache.json);for (int r = 0; r < g_region_cache.region_count; r++) {for (int f = 0; f < g_region_cache.region_file_count[r]; f++)- free(g_region_cache.region_files[r][f]);- free(g_region_cache.region_files[r]);+ cbm_free(CBM_MEM_CLASS_OTHER, g_region_cache.region_files[r][f]);+ cbm_free(CBM_MEM_CLASS_OTHER, g_region_cache.region_files[r]);}- free(g_region_cache.region_files);- free(g_region_cache.region_file_count);+ cbm_free(CBM_MEM_CLASS_OTHER, g_region_cache.region_files);+ cbm_free(CBM_MEM_CLASS_OTHER, g_region_cache.region_file_count);cbm_ht_free(g_region_cache.file_ht);memset(&g_region_cache, 0, sizeof(g_region_cache));}@@ -124,7 +126,7 @@ static char *rg_strdup(const char *s) {if (!s)return NULL;size_t len = strlen(s) + 1;- char *copy = malloc(len);+ char *copy = cbm_alloc(CBM_MEM_CLASS_OTHER, len);if (copy)memcpy(copy, s, len);return copy;@@ -234,21 +236,21 @@ static void rg_build_free(rg_build_t *b) {if (!b)return;for (int r = 0; r < b->region_count; r++) {- free(b->regions[r].name);- free(b->regions[r].hub);- free(b->regions[r].why);+ cbm_free(CBM_MEM_CLASS_OTHER, b->regions[r].name);+ cbm_free(CBM_MEM_CLASS_OTHER, b->regions[r].hub);+ cbm_free(CBM_MEM_CLASS_OTHER, b->regions[r].why);for (int t = 0; t < b->regions[r].top_count; t++)- free(b->regions[r].top_nodes[t]);+ cbm_free(CBM_MEM_CLASS_OTHER, b->regions[r].top_nodes[t]);}- free(b->regions);- free(b->edge_w);- free(b->node_map);+ cbm_free(CBM_MEM_CLASS_OTHER, b->regions);+ cbm_free(CBM_MEM_CLASS_OTHER, b->edge_w);+ cbm_free(CBM_MEM_CLASS_OTHER, b->node_map);for (int f = 0; f < b->file_count; f++) {- free(b->file_paths[f]);- free(b->file_recs[f]);+ cbm_free(CBM_MEM_CLASS_OTHER, b->file_paths[f]);+ cbm_free(CBM_MEM_CLASS_OTHER, b->file_recs[f]);}- free(b->file_paths);- free(b->file_recs);+ cbm_free(CBM_MEM_CLASS_OTHER, b->file_paths);+ cbm_free(CBM_MEM_CLASS_OTHER, b->file_recs);memset(b, 0, sizeof(*b));}@@ -259,10 +261,11 @@ static file_rec_t *rg_file_intern(CBMHashTable *ht, rg_build_t *b, int *cap, conreturn rec;if (b->file_count >= *cap) {int nc = *cap ? *cap * 2 : 1024;- char **np = realloc(b->file_paths, (size_t)nc * sizeof(char *));- file_rec_t **nr = realloc(b->file_recs, (size_t)nc * sizeof(file_rec_t *));+ char **np = cbm_realloc(CBM_MEM_CLASS_OTHER, b->file_paths, (size_t)nc * sizeof(char *));+ file_rec_t **nr =+ cbm_realloc(CBM_MEM_CLASS_OTHER, b->file_recs, (size_t)nc * sizeof(file_rec_t *));if (!np || !nr) {- free(np ? np : b->file_paths);+ cbm_free(CBM_MEM_CLASS_OTHER, np ? np : b->file_paths);b->file_paths = np ? np : NULL;if (nr)b->file_recs = nr;@@ -272,11 +275,11 @@ static file_rec_t *rg_file_intern(CBMHashTable *ht, rg_build_t *b, int *cap, conb->file_recs = nr;*cap = nc;}- rec = calloc(1, sizeof(*rec));+ rec = cbm_atlas_calloc_array(1, sizeof(*rec));char *owned = rg_strdup(path);if (!rec || !owned) {- free(rec);- free(owned);+ cbm_free(CBM_MEM_CLASS_OTHER, rec);+ cbm_free(CBM_MEM_CLASS_OTHER, owned);return NULL;}rec->idx = b->file_count;@@ -317,8 +320,9 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabchar **cnames = NULL;int cn = 0, ccap = 0;sqlite3_stmt *st = NULL;- const char *nsql = "SELECT id, name, file_path FROM nodes WHERE project=?1 AND label IN ("- CBM_SQL_CALLABLE_OR_TYPE_LABELS ") AND file_path IS NOT NULL ORDER BY id LIMIT ?2";+ const char *nsql =+ "SELECT id, name, file_path FROM nodes WHERE project=?1 AND label IN "+ "(" CBM_SQL_CALLABLE_OR_TYPE_LABELS ") AND file_path IS NOT NULL ORDER BY id LIMIT ?2";if (sqlite3_prepare_v2(db, nsql, -1, &st, NULL) != SQLITE_OK)return -1;sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);@@ -332,13 +336,13 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabbreak;if (cn >= ccap) {int nc = ccap ? ccap * 2 : 4096;- int64_t *ni = realloc(cids, (size_t)nc * sizeof(int64_t));- int *nf = realloc(cfile, (size_t)nc * sizeof(int));- char **nn = realloc(cnames, (size_t)nc * sizeof(char *));+ int64_t *ni = cbm_realloc(CBM_MEM_CLASS_OTHER, cids, (size_t)nc * sizeof(int64_t));+ int *nf = cbm_realloc(CBM_MEM_CLASS_OTHER, cfile, (size_t)nc * sizeof(int));+ char **nn = cbm_realloc(CBM_MEM_CLASS_OTHER, cnames, (size_t)nc * sizeof(char *));if (!ni || !nf || !nn) {- free(ni ? ni : cids);- free(nf ? nf : cfile);- free(nn ? nn : cnames);+ cbm_free(CBM_MEM_CLASS_OTHER, ni ? ni : cids);+ cbm_free(CBM_MEM_CLASS_OTHER, nf ? nf : cfile);+ cbm_free(CBM_MEM_CLASS_OTHER, nn ? nn : cnames);cids = NULL;cfile = NULL;cnames = NULL;@@ -360,11 +364,11 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabbool use_leiden = cn > 0 && cn <= REGION_LEIDEN_NODE_CAP;int *ccomm = NULL; /* community per callable */int community_count = 0;- int *cdeg = calloc(cn > 0 ? (size_t)cn : 1, sizeof(int));+ int *cdeg = cbm_atlas_calloc_array(cn > 0 ? (size_t)cn : 1, sizeof(int));if (use_leiden && cdeg) {/* CALLS edges among the callable set. */- rg_id_region_t *idmap = malloc((size_t)cn * sizeof(rg_id_region_t));+ rg_id_region_t *idmap = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)cn * sizeof(rg_id_region_t));cbm_louvain_edge_t *ledges = NULL;int le = 0, lcap = 0;if (idmap) {@@ -386,7 +390,8 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabcontinue;if (le >= lcap) {int nc = lcap ? lcap * 2 : 4096;- cbm_louvain_edge_t *ne = realloc(ledges, (size_t)nc * sizeof(*ledges));+ cbm_louvain_edge_t *ne =+ cbm_realloc(CBM_MEM_CLASS_OTHER, ledges, (size_t)nc * sizeof(*ledges));if (!ne)break;ledges = ne;@@ -403,9 +408,9 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTab}cbm_louvain_result_t *res = NULL;int rn = 0;- if (idmap &&- cbm_leiden(cids, cn, ledges, le, 1.0, &res, &rn) == CBM_STORE_OK && res && rn == cn) {- ccomm = malloc((size_t)cn * sizeof(int));+ if (idmap && cbm_leiden(cids, cn, ledges, le, 1.0, &res, &rn) == CBM_STORE_OK && res &&+ rn == cn) {+ ccomm = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)cn * sizeof(int));if (ccomm) {for (int i = 0; i < cn; i++) {ccomm[i] = res[i].community;@@ -414,14 +419,14 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTab}}}- free(res);- free(ledges);- free(idmap);+ cbm_free(CBM_MEM_CLASS_OTHER, res);+ cbm_free(CBM_MEM_CLASS_OTHER, ledges);+ cbm_free(CBM_MEM_CLASS_OTHER, idmap);}/* 2. Per-file community vote (majority; ties break on lower community). */if (ccomm && community_count > 0 && b->file_count > 0) {- rg_vote_t *votes = malloc((size_t)cn * sizeof(rg_vote_t));+ rg_vote_t *votes = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)cn * sizeof(rg_vote_t));if (votes) {for (int i = 0; i < cn; i++) {votes[i].file_idx = cfile[i];@@ -448,39 +453,43 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabb->file_recs[f]->votes = best_votes;i = j;}- free(votes);+ cbm_free(CBM_MEM_CLASS_OTHER, votes);}}/* 3. Community → file counts; keep the biggest as Leiden regions. */- int *comm_files = community_count > 0 ? calloc((size_t)community_count, sizeof(int)) : NULL;+ int *comm_files =+ community_count > 0 ? cbm_atlas_calloc_array((size_t)community_count, sizeof(int)) : NULL;if (comm_files) {for (int f = 0; f < b->file_count; f++)if (b->file_recs[f]->community >= 0)comm_files[b->file_recs[f]->community]++;}- int *comm_region = community_count > 0 ? malloc((size_t)community_count * sizeof(int)) : NULL;+ int *comm_region = community_count > 0+ ? cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)community_count * sizeof(int))+ : NULL;if (comm_region)for (int c = 0; c < community_count; c++)comm_region[c] = -1;- region_t *regions = calloc(REGION_MAX_TOTAL, sizeof(region_t));+ region_t *regions = cbm_atlas_calloc_array(REGION_MAX_TOTAL, sizeof(region_t));int region_count = 0;if (!regions) {- free(comm_files);- free(comm_region);+ cbm_free(CBM_MEM_CLASS_OTHER, comm_files);+ cbm_free(CBM_MEM_CLASS_OTHER, comm_region);for (int i = 0; i < cn; i++)- free(cnames[i]);- free(cnames);- free(cids);- free(cfile);- free(cdeg);- free(ccomm);+ cbm_free(CBM_MEM_CLASS_OTHER, cnames[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, cnames);+ cbm_free(CBM_MEM_CLASS_OTHER, cids);+ cbm_free(CBM_MEM_CLASS_OTHER, cfile);+ cbm_free(CBM_MEM_CLASS_OTHER, cdeg);+ cbm_free(CBM_MEM_CLASS_OTHER, ccomm);return -1;}if (comm_files && comm_region) {- rg_rank_t *rank = malloc((size_t)community_count * sizeof(rg_rank_t));+ rg_rank_t *rank =+ cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)community_count * sizeof(rg_rank_t));if (rank) {for (int c = 0; c < community_count; c++)rank[c] = (rg_rank_t){c, comm_files[c]};@@ -492,7 +501,7 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabregions[region_count].files = rank[r].files;region_count++;}- free(rank);+ cbm_free(CBM_MEM_CLASS_OTHER, rank);}}@@ -524,11 +533,13 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabif (!slot) {if (folder_count >= folder_cap) {int nc = folder_cap ? folder_cap * 2 : 64;- char **nk = realloc(folder_keys, (size_t)nc * sizeof(char *));- int *nf = realloc(folder_files, (size_t)nc * sizeof(int));+ char **nk =+ cbm_realloc(CBM_MEM_CLASS_OTHER, folder_keys, (size_t)nc * sizeof(char *));+ int *nf =+ cbm_realloc(CBM_MEM_CLASS_OTHER, folder_files, (size_t)nc * sizeof(int));if (!nk || !nf) {- free(nk ? nk : folder_keys);- free(nf ? nf : folder_files);+ cbm_free(CBM_MEM_CLASS_OTHER, nk ? nk : folder_keys);+ cbm_free(CBM_MEM_CLASS_OTHER, nf ? nf : folder_files);folder_keys = NULL;folder_files = NULL;folder_count = 0;@@ -551,13 +562,13 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTab}}if (folder_count > 0) {- rg_rank_t *rank = malloc((size_t)folder_count * sizeof(rg_rank_t));+ rg_rank_t *rank = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)folder_count * sizeof(rg_rank_t));if (rank) {for (int i = 0; i < folder_count; i++)rank[i] = (rg_rank_t){i, folder_files[i]};qsort(rank, (size_t)folder_count, sizeof(rg_rank_t), rg_rank_cmp);/* folder slot → region id, only for kept groups */- int *folder_region = malloc((size_t)folder_count * sizeof(int));+ int *folder_region = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)folder_count * sizeof(int));if (folder_region) {for (int i = 0; i < folder_count; i++)folder_region[i] = -1;@@ -583,15 +594,15 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabb->file_recs[f]->region = fr;}}- free(folder_region);+ cbm_free(CBM_MEM_CLASS_OTHER, folder_region);}- free(rank);+ cbm_free(CBM_MEM_CLASS_OTHER, rank);}}for (int i = 0; i < folder_count; i++)- free(folder_keys[i]);- free(folder_keys);- free(folder_files);+ cbm_free(CBM_MEM_CLASS_OTHER, folder_keys[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, folder_keys);+ cbm_free(CBM_MEM_CLASS_OTHER, folder_files);cbm_ht_free(folder_ht);/* 5. Misc region for whatever is left (created lazily in the node pass@@ -631,7 +642,8 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabif (!canon) {if (dir_count >= dir_cap) {int nc = dir_cap ? dir_cap * 2 : 32;- char **nk = realloc(dir_keys, (size_t)nc * sizeof(char *));+ char **nk =+ cbm_realloc(CBM_MEM_CLASS_OTHER, dir_keys, (size_t)nc * sizeof(char *));if (!nk)break;dir_keys = nk;@@ -647,7 +659,7 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabcbm_ht_set(dir_ht, canon, (void *)(intptr_t)cnt);if (cnt > best) {best = cnt;- free(best_key);+ cbm_free(CBM_MEM_CLASS_OTHER, best_key);best_key = rg_strdup(canon);}}@@ -659,16 +671,18 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabregions[r].name ? regions[r].name : "?");regions[r].why = rg_strdup(why);for (int d = 0; d < dir_count; d++)- free(dir_keys[d]);- free(dir_keys);+ cbm_free(CBM_MEM_CLASS_OTHER, dir_keys[d]);+ cbm_free(CBM_MEM_CLASS_OTHER, dir_keys);cbm_ht_free(dir_ht);}/* Top-k per region: the k highest-degree callables (name + hub). */{int k = REGION_TOP_NODES;- int *top_deg = malloc((size_t)region_count * (size_t)k * sizeof(int));- int *top_idx = malloc((size_t)region_count * (size_t)k * sizeof(int));+ int *top_deg =+ cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)region_count * (size_t)k * sizeof(int));+ int *top_idx =+ cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)region_count * (size_t)k * sizeof(int));if (top_deg && top_idx) {for (int i = 0; i < region_count * k; i++) {top_deg[i] = -1;@@ -703,19 +717,19 @@ static int rg_assign_regions(cbm_store_t *store, const char *project, CBMHashTabregions[r].hub = rg_strdup(regions[r].top_nodes[0]);}}- free(top_deg);- free(top_idx);+ cbm_free(CBM_MEM_CLASS_OTHER, top_deg);+ cbm_free(CBM_MEM_CLASS_OTHER, top_idx);}for (int i = 0; i < cn; i++)- free(cnames[i]);- free(cnames);- free(cids);- free(cfile);- free(cdeg);- free(ccomm);- free(comm_files);- free(comm_region);+ cbm_free(CBM_MEM_CLASS_OTHER, cnames[i]);+ cbm_free(CBM_MEM_CLASS_OTHER, cnames);+ cbm_free(CBM_MEM_CLASS_OTHER, cids);+ cbm_free(CBM_MEM_CLASS_OTHER, cfile);+ cbm_free(CBM_MEM_CLASS_OTHER, cdeg);+ cbm_free(CBM_MEM_CLASS_OTHER, ccomm);+ cbm_free(CBM_MEM_CLASS_OTHER, comm_files);+ cbm_free(CBM_MEM_CLASS_OTHER, comm_region);b->regions = regions;b->region_count = region_count;@@ -777,7 +791,8 @@ static int rg_map_all_nodes(cbm_store_t *store, const char *project, CBMHashTabl}if (n >= cap) {long long nc = cap ? cap * 2 : 65536;- rg_id_region_t *nm = realloc(map, (size_t)nc * sizeof(rg_id_region_t));+ rg_id_region_t *nm =+ cbm_realloc(CBM_MEM_CLASS_OTHER, map, (size_t)nc * sizeof(rg_id_region_t));if (!nm)break;map = nm;@@ -804,13 +819,13 @@ static int rg_map_all_nodes(cbm_store_t *store, const char *project, CBMHashTabl/* Edge pass: aggregate weights between regions across ALL edge types. */static int rg_aggregate_edges(cbm_store_t *store, const char *project, rg_build_t *b) {int rc2 = b->region_count * b->region_count;- b->edge_w = calloc(rc2 > 0 ? (size_t)rc2 : 1, sizeof(long long));+ b->edge_w = cbm_atlas_calloc_array(rc2 > 0 ? (size_t)rc2 : 1, sizeof(long long));if (!b->edge_w)return -1;struct sqlite3 *db = cbm_store_get_db(store);sqlite3_stmt *st = NULL;- if (!db || sqlite3_prepare_v2(db, "SELECT source_id, target_id FROM edges WHERE project=?1",- -1, &st, NULL) != SQLITE_OK)+ if (!db || sqlite3_prepare_v2(db, "SELECT source_id, target_id FROM edges WHERE project=?1", -1,+ &st, NULL) != SQLITE_OK)return -1;sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);while (sqlite3_step(st) == SQLITE_ROW) {@@ -834,7 +849,8 @@ static int rg_aggregate_edges(cbm_store_t *store, const char *project, rg_build_* by log2(weight) so heavy couplings pull harder. Deterministic. */static void rg_layout(rg_build_t *b, float *out_xyz, float *out_size) {int rc = b->region_count;- cbm_layout_body_t *bodies = calloc(rc > 0 ? (size_t)rc : 1, sizeof(cbm_layout_body_t));+ cbm_layout_body_t *bodies =+ cbm_atlas_calloc_array(rc > 0 ? (size_t)rc : 1, sizeof(cbm_layout_body_t));if (!bodies)return;long long max_members = 1;@@ -869,11 +885,11 @@ static void rg_layout(rg_build_t *b, float *out_xyz, float *out_size) {for (int k = 0; k < rep; k++) {if (ne >= ecap) {int nc = ecap ? ecap * 2 : 256;- int *ns = realloc(es, (size_t)nc * sizeof(int));- int *nd = realloc(ed, (size_t)nc * sizeof(int));+ int *ns = cbm_realloc(CBM_MEM_CLASS_OTHER, es, (size_t)nc * sizeof(int));+ int *nd = cbm_realloc(CBM_MEM_CLASS_OTHER, ed, (size_t)nc * sizeof(int));if (!ns || !nd) {- free(ns ? ns : es);- free(nd ? nd : ed);+ cbm_free(CBM_MEM_CLASS_OTHER, ns ? ns : es);+ cbm_free(CBM_MEM_CLASS_OTHER, nd ? nd : ed);es = NULL;ed = NULL;ne = 0;@@ -899,9 +915,9 @@ layout:double frac = max_members > 0 ? (double)b->regions[r].members / (double)max_members : 0.0;out_size[r] = 14.0f + (float)(sqrt(frac) * 46.0);}- free(es);- free(ed);- free(bodies);+ cbm_free(CBM_MEM_CLASS_OTHER, es);+ cbm_free(CBM_MEM_CLASS_OTHER, ed);+ cbm_free(CBM_MEM_CLASS_OTHER, bodies);}/* Serialize the build to the level=regions payload. */@@ -958,7 +974,7 @@ static char *rg_to_json(const rg_build_t *b, const float *xyz, const float *size}}yyjson_mut_obj_add_val(doc, root, "edges", earr);- char *json = yyjson_mut_write(doc, 0, NULL);+ char *json = yyjson_mut_write_opts(doc, 0, cbm_json_writer_allocator(), NULL, NULL);yyjson_mut_doc_free(doc);return json;}@@ -977,14 +993,16 @@ static int rg_rebuild_locked(cbm_store_t *store, const char *project, const charrc = rg_aggregate_edges(store, project, &b);char *json = NULL;if (rc == 0) {- float *xyz = calloc(b.region_count > 0 ? (size_t)b.region_count * 3 : 1, sizeof(float));- float *size = calloc(b.region_count > 0 ? (size_t)b.region_count : 1, sizeof(float));+ float *xyz = cbm_atlas_calloc_array(b.region_count > 0 ? (size_t)b.region_count * 3 : 1,+ sizeof(float));+ float *size =+ cbm_atlas_calloc_array(b.region_count > 0 ? (size_t)b.region_count : 1, sizeof(float));if (xyz && size) {rg_layout(&b, xyz, size);json = rg_to_json(&b, xyz, size);}- free(xyz);- free(size);+ cbm_free(CBM_MEM_CLASS_OTHER, xyz);+ cbm_free(CBM_MEM_CLASS_OTHER, size);}if (!json) {rg_build_free(&b);@@ -998,10 +1016,10 @@ static int rg_rebuild_locked(cbm_store_t *store, const char *project, const charg_region_cache.json = json;g_region_cache.region_count = b.region_count;g_region_cache.total_nodes = b.total_nodes;- g_region_cache.region_files = calloc(b.region_count > 0 ? (size_t)b.region_count : 1,- sizeof(char **));- g_region_cache.region_file_count = calloc(b.region_count > 0 ? (size_t)b.region_count : 1,- sizeof(int));+ g_region_cache.region_files =+ cbm_atlas_calloc_array(b.region_count > 0 ? (size_t)b.region_count : 1, sizeof(char **));+ g_region_cache.region_file_count =+ cbm_atlas_calloc_array(b.region_count > 0 ? (size_t)b.region_count : 1, sizeof(int));g_region_cache.file_ht = cbm_ht_create((uint32_t)(b.file_count > 0 ? b.file_count : 16));if (g_region_cache.region_files && g_region_cache.region_file_count) {for (int f = 0; f < b.file_count; f++) {@@ -1009,8 +1027,8 @@ static int rg_rebuild_locked(cbm_store_t *store, const char *project, const charif (r < 0 || r >= b.region_count)continue;int idx = g_region_cache.region_file_count[r];- char **grown = realloc(g_region_cache.region_files[r],- ((size_t)idx + 1) * sizeof(char *));+ char **grown = cbm_realloc(CBM_MEM_CLASS_OTHER, g_region_cache.region_files[r],+ ((size_t)idx + 1) * sizeof(char *));if (!grown)continue;g_region_cache.region_files[r] = grown;@@ -1070,7 +1088,7 @@ cbm_layout_result_t *cbm_layout_compute_region(cbm_store_t *store, const char *p}/* Copy the file list out so the store queries run unlocked. */int file_count = g_region_cache.region_file_count[region_id];- char **files = calloc(file_count > 0 ? (size_t)file_count : 1, sizeof(char *));+ char **files = cbm_atlas_calloc_array(file_count > 0 ? (size_t)file_count : 1, sizeof(char *));if (!files) {pthread_mutex_unlock(&g_region_mu);return NULL;@@ -1096,8 +1114,7 @@ cbm_layout_result_t *cbm_layout_compute_region(cbm_store_t *store, const char *p"end_line, properties FROM nodes WHERE project=?1 AND file_path ""IN (");for (int i = 0; i < cnt && pos < (int)sizeof(sql) - 8; i++)- pos += snprintf(sql + pos, sizeof(sql) - (size_t)pos, "%s?%d", i ? "," : "",- i + 2);+ pos += snprintf(sql + pos, sizeof(sql) - (size_t)pos, "%s?%d", i ? "," : "", i + 2);snprintf(sql + pos, sizeof(sql) - (size_t)pos, ") ORDER BY id");sqlite3_stmt *st = NULL;if (sqlite3_prepare_v2(db, sql, -1, &st, NULL) != SQLITE_OK)@@ -1111,7 +1128,8 @@ cbm_layout_result_t *cbm_layout_compute_region(cbm_store_t *store, const char *pcontinue; /* keep counting the region total */if (n >= cap) {int nc = cap ? cap * 2 : 1024;- cbm_node_t *nn = realloc(nodes, (size_t)nc * sizeof(cbm_node_t));+ cbm_node_t *nn =+ cbm_realloc(CBM_MEM_CLASS_OTHER, nodes, (size_t)nc * sizeof(cbm_node_t));if (!nn)break;nodes = nn;@@ -1133,19 +1151,19 @@ cbm_layout_result_t *cbm_layout_compute_region(cbm_store_t *store, const char *p}}for (int f = 0; f < file_count; f++)- free(files[f]);- free(files);+ cbm_free(CBM_MEM_CLASS_OTHER, files[f]);+ cbm_free(CBM_MEM_CLASS_OTHER, files);cbm_layout_result_t *result =cbm_layout_from_nodes(store, project, nodes, n, (int)region_total);for (int i = 0; i < n; i++) {- free((void *)nodes[i].label);- free((void *)nodes[i].name);- free((void *)nodes[i].qualified_name);- free((void *)nodes[i].file_path);- free((void *)nodes[i].properties_json);+ cbm_free(CBM_MEM_CLASS_OTHER, (void *)nodes[i].label);+ cbm_free(CBM_MEM_CLASS_OTHER, (void *)nodes[i].name);+ cbm_free(CBM_MEM_CLASS_OTHER, (void *)nodes[i].qualified_name);+ cbm_free(CBM_MEM_CLASS_OTHER, (void *)nodes[i].file_path);+ cbm_free(CBM_MEM_CLASS_OTHER, (void *)nodes[i].properties_json);}- free(nodes);+ cbm_free(CBM_MEM_CLASS_OTHER, nodes);return result;}diff --git a/tests/test_architecture_projection.c b/tests/test_architecture_projection.cindex 088990a9f..68a49995b 100644--- a/tests/test_architecture_projection.c+++ b/tests/test_architecture_projection.c@@ -1,4 +1,8 @@#include "test_framework.h"+#include "test_helpers.h"+#include "foundation/compat.h"+#include "foundation/mem_core.h"+#include "mcp/architecture_jobs.h"#include <store/architecture_projection.h>#include <foundation/platform.h>#include <yyjson/yyjson.h>@@ -57,7 +61,7 @@ TEST(projection_accounts_for_isolated_nodes_and_files) {ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 2);ASSERT_EQ(yyjson_arr_size(projection_field(doc, "dependencies")), 0);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -90,7 +94,7 @@ TEST(projection_preserves_typed_edges_and_contiguous_paths) {ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(edges, 0), "id")), first);ASSERT_EQ(yyjson_arr_size(projection_field(doc, "dependencies")), 2);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* A real binding changes the answer; projected component edges alone did not. */projection_edge(store, b1, b2, "CALLS");ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);@@ -100,7 +104,7 @@ TEST(projection_preserves_typed_edges_and_contiguous_paths) {ASSERT_EQ(yyjson_arr_size(nodes), 4);ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(nodes, 3), "id")), c);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -126,7 +130,7 @@ TEST(projection_reports_dependency_cycles_without_fabricated_execution) {ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(yyjson_arr_get(cycles, 0), "component_ids")), 3);ASSERT_EQ(yyjson_arr_size(projection_field(doc, "paths")), 0);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_architecture_projection_options_t opts = {.max_components = 2};ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);doc = yyjson_read(json, strlen(json), 0);@@ -135,7 +139,7 @@ TEST(projection_reports_dependency_cycles_without_fabricated_execution) {ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "cycles")), 1);ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "limits"), "omitted_cycles")), 1);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -157,7 +161,7 @@ TEST(projection_graph_limits_abstain_instead_of_sampling) {ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 0);ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "nodes")), 2);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);opts.max_nodes = 0;opts.max_edges = 1;ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);@@ -166,7 +170,7 @@ TEST(projection_graph_limits_abstain_instead_of_sampling) {ASSERT_STR_EQ(yyjson_get_str(projection_field(doc, "status")), "limited");ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 0);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -192,7 +196,7 @@ TEST(projection_cancellation_deadline_and_store_reuse) {ASSERT_NULL(json);ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);ASSERT_NOT_NULL(json);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);ASSERT_EQ(sqlite3_get_autocommit(cbm_store_get_db(store)), 1);cbm_store_close(store);PASS();@@ -217,7 +221,7 @@ TEST(projection_display_caps_preserve_total_accounting) {2);ASSERT_FALSE(yyjson_get_bool(projection_field(doc, "complete")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -234,7 +238,7 @@ TEST(projection_unknown_project_and_empty_project) {ASSERT_TRUE(yyjson_get_bool(projection_field(doc, "complete")));ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 0);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);projection_node(store, "Project", "projection", "", false);projection_node(store, "Folder", "projection.folder", "folder", false);ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);@@ -245,7 +249,7 @@ TEST(projection_unknown_project_and_empty_project) {ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "structural_nodes")),2);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -271,7 +275,7 @@ TEST(projection_paths_depth_cap_is_explicit) {yyjson_val *path = yyjson_arr_get(projection_field(doc, "paths"), 0);ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(path, "edges")), 2);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -296,7 +300,7 @@ TEST(projection_channel_relationships_are_typed_not_fake_calls) {ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "unmodeled_edges")),1);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -343,7 +347,7 @@ TEST(projection_test_callers_cannot_absorb_source_components) {ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "accounted_nodes")),10);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -381,7 +385,7 @@ TEST(projection_indexed_embedded_test_has_separate_membership) {}ASSERT_TRUE(found);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -417,7 +421,7 @@ TEST(projection_shallow_leaves_do_not_hide_deeper_behavior) {ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(projection_field(doc, "limits"), "paths_truncated")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -449,7 +453,7 @@ TEST(projection_behavior_preserves_first_hop_diversity) {int64_t hop2 = yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(second, 1), "id"));ASSERT_TRUE((hop1 == a && hop2 == b) || (hop1 == b && hop2 == a));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -530,7 +534,7 @@ TEST(projection_corridor_preserves_joins_cycles_and_callsite_evidence) {}}yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);opts.target_node_id = ignored;ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);doc = yyjson_read(json, strlen(json), 0);@@ -541,7 +545,7 @@ TEST(projection_corridor_preserves_joins_cycles_and_callsite_evidence) {ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(view, "nodes")), 0);ASSERT_EQ(yyjson_arr_size(projection_field(doc, "paths")), 0);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -568,7 +572,7 @@ TEST(projection_corridor_caps_abstain_without_hiding_joins) {ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(view, "edges")), 0);ASSERT_EQ(yyjson_arr_size(projection_field(doc, "paths")), 0);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);opts.target_node_id = 0;opts.max_targets = 1;ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);@@ -579,7 +583,7 @@ TEST(projection_corridor_caps_abstain_without_hiding_joins) {ASSERT_EQ(yyjson_get_int(yyjson_obj_get(yyjson_obj_get(view, "totals"), "omitted_targets")), 1);ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(view, "complete")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -626,7 +630,7 @@ TEST(projection_overview_accounts_for_components_beyond_legacy_cap) {char stable[128];snprintf(stable, sizeof(stable), "%s", group_id);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);opts.target_node_id = target;ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);doc = yyjson_read(json, strlen(json), 0);@@ -637,7 +641,7 @@ TEST(projection_overview_accounts_for_components_beyond_legacy_cap) {ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(projection_field(doc, "overview"), "components")),302);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -659,7 +663,7 @@ TEST(projection_aggregate_cycle_does_not_invent_symbol_cycle) {ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(projection_field(doc, "overview"), "connections")), 2);ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(projection_field(doc, "behavior"), "cycles")), 0);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -709,7 +713,7 @@ TEST(projection_provenance_budget_counts_utf8_bytes) {}}yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -761,7 +765,7 @@ TEST(projection_example_budgets_preserve_full_aggregate_counts) {ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(connection, "witnesses")), 1);ASSERT_EQ(yyjson_get_int(yyjson_obj_get(connection, "omitted_witnesses")), 4);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -871,7 +875,7 @@ TEST(projection_behavior_evidence_is_opt_in_and_shared_across_surfaces) {ASSERT_NULL(strstr(json, "\"arguments\""));ASSERT_NULL(strstr(json, "\"argument_limit\""));ASSERT_EQ(queries, 0);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);opts.include_behavior_evidence = true;ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);@@ -884,7 +888,7 @@ TEST(projection_behavior_evidence_is_opt_in_and_shared_across_surfaces) {ASSERT_TRUE(queries > 0);ASSERT_TRUE(queries <= 4); /* cache once per displayed indexed node */yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);queries = 0;opts.include_behavior_evidence = false;@@ -892,7 +896,7 @@ TEST(projection_behavior_evidence_is_opt_in_and_shared_across_surfaces) {ASSERT_NULL(strstr(json, "\"return_type\""));ASSERT_NULL(strstr(json, "\"arguments\""));ASSERT_EQ(queries, 0);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);sqlite3_trace_v2(cbm_store_get_db(store), 0, NULL, NULL);cbm_store_close(store);PASS();@@ -958,7 +962,7 @@ TEST(projection_argument_validation_keeps_exact_edge_and_callsite_identity) {ASSERT_EQ(seen, 2);ASSERT_NULL(strstr(json, "ninth"));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -999,7 +1003,7 @@ TEST(projection_missing_corrupt_and_noncall_arguments_remain_unknown) {ASSERT_NULL(strstr(json, "\"parameters\""));ASSERT_NOT_NULL(strstr(json, "\"return_type\":\"Known\""));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);}cbm_store_t *store = projection_store();@@ -1018,7 +1022,7 @@ TEST(projection_missing_corrupt_and_noncall_arguments_remain_unknown) {char *json = NULL;ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);ASSERT_NULL(strstr(json, "\"arguments\""));- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -1062,7 +1066,7 @@ TEST(projection_oversized_evidence_is_omitted_without_truncating_values) {ASSERT_NULL(yyjson_obj_get(arg, "v"));ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(edge, "arguments_complete")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -1134,8 +1138,8 @@ TEST(projection_repeated_behavior_evidence_preserves_base_graph_under_budget) {ASSERT_NOT_NULL(strstr(enriched_json, "Optional behavior evidence was omitted"));yyjson_doc_free(baseline);yyjson_doc_free(enriched);- free(baseline_json);- free(enriched_json);+ cbm_free(CBM_MEM_CLASS_OTHER, baseline_json);+ cbm_free(CBM_MEM_CLASS_OTHER, enriched_json);cbm_store_close(store);PASS();}@@ -1226,7 +1230,7 @@ TEST(projection_many_small_components_stay_within_response_budget) {ASSERT_EQ(membership, parts);ASSERT_EQ(members, parts);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -1288,7 +1292,7 @@ TEST(projection_python_test_files_follow_name_conventions) {ASSERT_EQ(yyjson_get_int(yyjson_obj_get(api, "member_count")), 2);ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 7);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -1354,12 +1358,95 @@ TEST(projection_route_handlers_are_entry_points) {yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(yyjson_obj_get(second, "nodes"), 1), "id")),query);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}+TEST(projection_response_memory_returns_to_caller_baseline) {+ cbm_store_t *store = projection_store();+ ASSERT_NOT_NULL(store);+ projection_node(store, "File", "projection.a.c", "a.c", false);+ int64_t entry = projection_node(store, "Function", "projection.start", "a.c", true);+ int64_t target = projection_node(store, "Function", "projection.finish", "b.c", false);+ projection_edge(store, entry, target, "CALLS");+ cbm_architecture_projection_options_t options = {.entry_node_id = entry,+ .include_behavior_evidence = true};+ size_t blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ size_t bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ for (int limited = 0; limited < 2; limited++) {+ options.max_nodes = limited ? 1 : 0;+ char *json = NULL;+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &options, &json),+ CBM_STORE_OK);+ ASSERT_NOT_NULL(json);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), blocks + 1);+ ASSERT_EQ(cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER), bytes + cbm_mem_usable_size(json));+ cbm_free(CBM_MEM_CLASS_OTHER, json);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), blocks);+ ASSERT_EQ(cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER), bytes);+ }+ cbm_store_close(store);+ PASS();+}++TEST(projection_completed_job_memory_returns_to_caller_baseline) {+ char temp[256] = "/tmp/cbm_projection_memory_XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(temp));+ char path[1024];+ snprintf(path, sizeof(path), "%s/index.db", temp);+ cbm_store_t *store = cbm_store_open_path(path);+ ASSERT_NOT_NULL(store);+ ASSERT_EQ(cbm_store_upsert_project(store, "projection", temp), CBM_STORE_OK);+ projection_node(store, "Function", "projection.entry", "entry.c", true);++ /* A live caller allocation makes a lost worker delta observable even when+ * the shared counters would otherwise saturate at zero on cache release. */+ void *sentinel = cbm_alloc(CBM_MEM_CLASS_OTHER, 64);+ ASSERT_NOT_NULL(sentinel);+ size_t before_blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ size_t before_bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ cbm_architecture_jobs_t *jobs = cbm_architecture_jobs_new();+ ASSERT_NOT_NULL(jobs);+ bool ready = false, cached = false;+ uint64_t deadline = cbm_now_ms() + 10000;+ do {+ char *json = cbm_architecture_jobs_request(jobs, store, "projection", 0);+ yyjson_doc *doc = json ? yyjson_read(json, strlen(json), 0) : NULL;+ const char *status = doc ? yyjson_get_str(projection_field(doc, "status")) : NULL;+ ready = status && strcmp(status, "ready") == 0;+ bool pending = status && strcmp(status, "pending") == 0;+ yyjson_doc_free(doc);+ cbm_free(CBM_MEM_CLASS_OTHER, json);+ if (!pending)+ break;+ cbm_usleep(1000);+ } while (cbm_now_ms() < deadline);+ if (ready) {+ char *json = cbm_architecture_jobs_request(jobs, store, "projection", 0);+ yyjson_doc *doc = json ? yyjson_read(json, strlen(json), 0) : NULL;+ const char *status = doc ? yyjson_get_str(projection_field(doc, "status")) : NULL;+ cached = status && strcmp(status, "ready") == 0;+ yyjson_doc_free(doc);+ cbm_free(CBM_MEM_CLASS_OTHER, json);+ }+ cbm_architecture_jobs_free(jobs); /* joins before the caller frees retained output */+ size_t after_blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ size_t after_bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ cbm_free(CBM_MEM_CLASS_OTHER, sentinel);+ cbm_store_close(store);+ th_rmtree(temp);++ ASSERT_TRUE(ready);+ ASSERT_TRUE(cached);+ ASSERT_EQ(after_blocks, before_blocks);+ ASSERT_EQ(after_bytes, before_bytes);+ PASS();+}+SUITE(architecture_projection) {+ RUN_TEST(projection_completed_job_memory_returns_to_caller_baseline);+ RUN_TEST(projection_response_memory_returns_to_caller_baseline);RUN_TEST(projection_accounts_for_isolated_nodes_and_files);RUN_TEST(projection_preserves_typed_edges_and_contiguous_paths);RUN_TEST(projection_reports_dependency_cycles_without_fabricated_execution);diff --git a/tests/test_httpd.c b/tests/test_httpd.cindex b7447abed..c61abf9bb 100644--- a/tests/test_httpd.c+++ b/tests/test_httpd.c@@ -17,6 +17,7 @@#include "../src/foundation/compat_fs.h"#include "../src/foundation/compat_thread.h"#include "../src/foundation/log.h"+#include "../src/foundation/mem_core.h"#include "../src/foundation/platform.h"#include "../src/foundation/str_util.h" /* cbm_json_escape: expected index-status fragment */#include "../src/cli/cli.h"@@ -27,6 +28,8 @@#include "test_helpers.h"#include "ui/httpd.h"#include "ui/activity.h"+#include "ui/atlas.h"+#include "ui/layout3d.h"#include <yyjson/yyjson.h>#include "ui/http_server.h"#include <store/store.h>@@ -1125,6 +1128,34 @@ static int activity_interrupt_rows(unsigned kind, void *database, void *statemenreturn 0;}+TEST(activity_reply_memory_core_ownership) {+ sqlite3 *db = cbm_activity_open(":memory:");+ ASSERT_NOT_NULL(db);+ size_t before_blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ size_t before_bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ char *reply = cbm_activity_logs(db, -1, 10, 0);+ ASSERT_NOT_NULL(reply);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), before_blocks + 1);+ cbm_free(CBM_MEM_CLASS_OTHER, reply);+ reply = NULL;+ ASSERT_EQ(cbm_activity_ingest(db, "{", &reply), 400);+ ASSERT_NULL(reply);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), before_blocks);+ reply = NULL;+ ASSERT_EQ(cbm_activity_ingest(db, "{\"project\":\"memory-test\",\"events\":[]}", &reply), 200);+ ASSERT_NOT_NULL(reply);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), before_blocks + 1);+ cbm_free(CBM_MEM_CLASS_OTHER, reply);+ reply = cbm_activity_agents(db, "memory-test", 0, 10);+ ASSERT_NOT_NULL(reply);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), before_blocks + 1);+ cbm_free(CBM_MEM_CLASS_OTHER, reply);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), before_blocks);+ ASSERT_EQ(cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER), before_bytes);+ sqlite3_close(db);+ PASS();+}+TEST(activity_preserves_severity_and_reports_interrupted_reads) {sqlite3 *db = cbm_activity_open(":memory:");ASSERT_NOT_NULL(db);@@ -1134,7 +1165,7 @@ TEST(activity_preserves_severity_and_reports_interrupted_reads) {char *json = cbm_activity_logs(db, -1, 10, 2);ASSERT_NOT_NULL(json);ASSERT_NOT_NULL(strstr(json, "\"total\":0"));- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);ASSERT_EQ(sqlite3_trace_v2(db, SQLITE_TRACE_STMT, activity_interrupt_rows, db), SQLITE_OK);ASSERT_NULL(cbm_activity_logs(db, -1, 10, 0));ASSERT_NULL(cbm_activity_agents(db, "test", 0, 10));@@ -1151,7 +1182,7 @@ TEST(activity_pruned_start_events_do_not_resurrect_on_retry) {"\"Read\",\"seq\":1,\"ts\":1000,\"phase\":\"start\"}]}";char *reply = NULL;ASSERT_EQ(cbm_activity_ingest(db, batch, &reply), 200);- free(reply);+ cbm_free(CBM_MEM_CLASS_OTHER, reply);ASSERT_EQ(sqlite3_exec(db,@@ -1160,15 +1191,15 @@ TEST(activity_pruned_start_events_do_not_resurrect_on_retry) {NULL, NULL, NULL),SQLITE_OK);ASSERT_EQ(cbm_activity_ingest(db, "{\"project\":\"fixture-b\",\"events\":[]}", &reply), 200);- free(reply);+ cbm_free(CBM_MEM_CLASS_OTHER, reply);ASSERT_EQ(cbm_activity_ingest(db, batch, &reply), 200);ASSERT_NOT_NULL(strstr(reply, "\"accepted\":0"));ASSERT_NOT_NULL(strstr(reply, "\"duplicates\":1"));- free(reply);+ cbm_free(CBM_MEM_CLASS_OTHER, reply);reply = cbm_activity_agents(db, "fixture-a", 0, 10);ASSERT_NOT_NULL(strstr(reply, "\"events\":[]"));ASSERT_NOT_NULL(strstr(reply, "\"truncated\":true"));- free(reply);+ cbm_free(CBM_MEM_CLASS_OTHER, reply);sqlite3_close(db);PASS();}@@ -1196,14 +1227,14 @@ TEST(activity_migration_preserves_v1_logs_and_rejects_future_schema) {ASSERT_NOT_NULL(json);ASSERT_NOT_NULL(strstr(json, "preserved failure"));ASSERT_NOT_NULL(strstr(json, "\"total\":1"));- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);const char *ui = "{\"session\":\"migration-fixture\",\"seq\":1,\"level\":\"error\",\"source\":""\"frontend\",\"message\":\"retry-safe\"}";ASSERT_TRUE(cbm_activity_log(db, ui));ASSERT_TRUE(cbm_activity_log(db, ui));json = cbm_activity_logs(db, -1, 10, 2);ASSERT_NOT_NULL(strstr(json, "\"total\":2"));- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);ASSERT_EQ(sqlite3_exec(db, "PRAGMA user_version=99", NULL, NULL, NULL), SQLITE_OK);sqlite3_close(db);ASSERT_NULL(cbm_activity_open(path));@@ -1252,12 +1283,12 @@ TEST(activity_log_project_scope_preserves_unknown_v2_history_and_filters_before_ASSERT_NOT_NULL(strstr(page, "\"scope\":\"project\""));ASSERT_NULL(strstr(page, "unrelated flood"));ASSERT_NULL(strstr(page, "legacy"));- free(page);+ cbm_free(CBM_MEM_CLASS_OTHER, page);page = cbm_activity_logs_scoped(db, 0, 1, 2, "fixture-a", false);ASSERT_NOT_NULL(strstr(page, "first-a"));ASSERT_NOT_NULL(strstr(page, "\"cursor\":2"));ASSERT_NOT_NULL(strstr(page, "\"has_more\":true"));- free(page);+ cbm_free(CBM_MEM_CLASS_OTHER, page);sqlite3_close(db);db = cbm_activity_open(path);ASSERT_NOT_NULL(db);@@ -1265,17 +1296,17 @@ TEST(activity_log_project_scope_preserves_unknown_v2_history_and_filters_before_ASSERT_NOT_NULL(strstr(page, "last-a"));ASSERT_NOT_NULL(strstr(page, "\"cursor\":3"));ASSERT_NOT_NULL(strstr(page, "\"has_more\":false"));- free(page);+ cbm_free(CBM_MEM_CLASS_OTHER, page);page = cbm_activity_logs_scoped(db, -1, 10, 2, NULL, true);ASSERT_NOT_NULL(strstr(page, "legacy project=fixture-a"));ASSERT_NOT_NULL(strstr(page, "\"total\":3"));ASSERT_NOT_NULL(strstr(page, "\"project\":null"));ASSERT_NOT_NULL(strstr(page, "\"scope\":\"unattributed\""));- free(page);+ cbm_free(CBM_MEM_CLASS_OTHER, page);page = cbm_activity_logs(db, -1, 1, 2);ASSERT_NOT_NULL(strstr(page, "\"total\":605"));ASSERT_NOT_NULL(strstr(page, "\"scope\":\"daemon\""));- free(page);+ cbm_free(CBM_MEM_CLASS_OTHER, page);sqlite3_close(db);th_cleanup(dir);PASS();@@ -1350,14 +1381,14 @@ TEST(activity_log_search_and_severity_apply_before_limit_and_survive_reopen) {char *json = cbm_activity_logs(db, -1, 200, 0);ASSERT_NOT_NULL(json);ASSERT_NULL(strstr(json, "10%_broken"));- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);json = cbm_activity_logs_filtered(db, -1, 200, 3, "fixture-a", false, "10%_");ASSERT_NOT_NULL(json);ASSERT_NOT_NULL(strstr(json, "\"total\":49"));ASSERT_NOT_NULL(strstr(json, "\"query\":\"10%_\""));ASSERT_NOT_NULL(strstr(json, "10%_broken.c"));ASSERT_NULL(strstr(json, "routine"));- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);sqlite3_close(db);db = cbm_activity_open(path);ASSERT_NOT_NULL(db);@@ -1366,13 +1397,13 @@ TEST(activity_log_search_and_severity_apply_before_limit_and_survive_reopen) {ASSERT_NOT_NULL(strstr(json, "\"cursor\":1"));ASSERT_NOT_NULL(strstr(json, "\"has_more\":true"));ASSERT_NOT_NULL(strstr(json, "\"total\":49"));- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);json = cbm_activity_logs_filtered(db, 1, 1, 3, "fixture-a", false, "BROKEN");ASSERT_NOT_NULL(strstr(json, "\"cursor\":2"));- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);json = cbm_activity_logs_filtered(db, -1, 200, 3, "fixture-b", false, "10%_");ASSERT_NOT_NULL(strstr(json, "\"total\":0"));- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);sqlite3_close(db);th_cleanup(dir);PASS();@@ -1405,7 +1436,7 @@ TEST(ui_log_retention_prevents_expired_retry_and_preserves_full_json) {ASSERT_NOT_NULL(full);yyjson_doc_free(full);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);ASSERT_EQ(sqlite3_exec(db,"WITH RECURSIVE n(v) AS (SELECT 1 UNION ALL SELECT v+1 FROM n WHERE v<3000) "@@ -1421,7 +1452,7 @@ TEST(ui_log_retention_prevents_expired_retry_and_preserves_full_json) {ASSERT_EQ(cbm_activity_ui_log(db, message, false), 0);json = cbm_activity_ui_logs(db, 200, path, "", NULL);ASSERT_NOT_NULL(strstr(json, "\"total\":0"));- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);sqlite3_close(db);th_cleanup(dir);PASS();@@ -1535,10 +1566,10 @@ TEST(activity_journal_reopen_cursor_dedup_and_project_isolation) {char *reply = NULL;ASSERT_EQ(cbm_activity_ingest(db, batch, &reply), 200);ASSERT_NOT_NULL(strstr(reply, "\"accepted\":2"));- free(reply);+ cbm_free(CBM_MEM_CLASS_OTHER, reply);ASSERT_EQ(cbm_activity_ingest(db, batch, &reply), 200);ASSERT_NOT_NULL(strstr(reply, "\"duplicates\":2"));- free(reply);+ cbm_free(CBM_MEM_CLASS_OTHER, reply);char *page = cbm_activity_agents(db, "demo", 0, 1);ASSERT_NOT_NULL(page);ASSERT_NULL(strstr(page, "never-store-this"));@@ -1546,17 +1577,17 @@ TEST(activity_journal_reopen_cursor_dedup_and_project_isolation) {yyjson_doc *parsed = yyjson_read(page, strlen(page), 0);int64_t cursor = yyjson_get_sint(yyjson_obj_get(yyjson_doc_get_root(parsed), "cursor"));yyjson_doc_free(parsed);- free(page);+ cbm_free(CBM_MEM_CLASS_OTHER, page);sqlite3_close(db);db = cbm_activity_open(path);ASSERT_NOT_NULL(db);page = cbm_activity_agents(db, "demo", cursor, 10);ASSERT_NOT_NULL(strstr(page, "\"seq\":1"));ASSERT_NULL(strstr(page, "\"seq\":2"));- free(page);+ cbm_free(CBM_MEM_CLASS_OTHER, page);page = cbm_activity_agents(db, "other", 0, 10);ASSERT_NOT_NULL(strstr(page, "\"events\":[]"));- free(page);+ cbm_free(CBM_MEM_CLASS_OTHER, page);ASSERT_EQ(cbm_activity_ingest(db, "{\"events\":[{\"run\":\"bad\"}]}", &reply), 400);sqlite3_close(db);th_cleanup(dir);@@ -1580,14 +1611,14 @@ TEST(activity_errors_survive_routine_log_retention_and_reopen) {ASSERT_NOT_NULL(strstr(page, "\"level\":\"error\""));ASSERT_NOT_NULL(strstr(page, "\"total\":1"));ASSERT_NULL(strstr(page, "http.request"));- free(page);+ cbm_free(CBM_MEM_CLASS_OTHER, page);sqlite3_close(reader);sqlite3_close(db);db = cbm_activity_open(path);ASSERT_NOT_NULL(db);page = cbm_activity_logs(db, -1, 10, 0);ASSERT_NOT_NULL(strstr(page, "\"total\":3001"));- free(page);+ cbm_free(CBM_MEM_CLASS_OTHER, page);sqlite3_close(db);th_cleanup(dir);PASS();@@ -2394,6 +2425,64 @@ TEST(ui_server_atlas_routes_are_wired) {PASS();}+TEST(ui_server_retained_cache_memory_is_flushed_before_thread_exit) {+ cbm_atlas_metrics_cache_clear();+ cbm_atlas_flows_cache_clear();+ cbm_layout_regions_cache_clear();+ ui_delete_fixture_t fixture;+ ASSERT_EQ(ui_delete_fixture_init(&fixture), 0);+ char path[1024];+ ui_delete_db_path(&fixture, "http-memory", path, sizeof(path));+ cbm_store_t *store = cbm_store_open_path(path);+ ASSERT_NOT_NULL(store);+ ASSERT_EQ(cbm_store_upsert_project(store, "http-memory", ""), CBM_STORE_OK);+ /* Settle the independent history cache on the caller before measuring the+ * HTTP worker. An empty source root does not retain history-scan buffers. */+ char *warm = cbm_atlas_metrics_json(store, "http-memory");+ ASSERT_NOT_NULL(warm);+ cbm_free(CBM_MEM_CLASS_OTHER, warm);+ cbm_atlas_metrics_cache_clear();+ cbm_layout_regions_cache_clear();+ cbm_store_close(store);+ void *sentinel = cbm_alloc(CBM_MEM_CLASS_OTHER, 64);+ ASSERT_NOT_NULL(sentinel);+ th_server_t server;+ server.srv = cbm_http_server_new(0);+ ASSERT_NOT_NULL(server.srv);+ size_t before_blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ size_t before_bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ ASSERT_EQ(th_server_thread_start(&server.tid, server.srv), 0);+ char response[16384];+ int length = th_http(cbm_http_server_port(server.srv),+ "GET /api/metrics?project=http-memory HTTP/1.1\r\n\r\n", response,+ sizeof(response));+ bool metrics_ok = length > 0 && th_status(response) == 200;+ /* Receiving a second reply proves the first request reached its flush+ * boundary. It avoids asserting the listener's transient idle state. */+ length = th_http(cbm_http_server_port(server.srv), "GET /missing-memory-probe HTTP/1.1\r\n\r\n",+ response, sizeof(response));+ bool fence_ok = length > 0 && th_status(response) == 404;+ size_t retained_blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ cbm_http_server_stop(server.srv);+ int joined = cbm_thread_join(&server.tid);+ cbm_atlas_metrics_cache_clear();+ cbm_atlas_flows_cache_clear();+ cbm_layout_regions_cache_clear();+ size_t after_blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ size_t after_bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ bool freed = cbm_http_server_free(server.srv);+ cbm_free(CBM_MEM_CLASS_OTHER, sentinel);+ ui_delete_fixture_cleanup(&fixture);+ ASSERT_TRUE(metrics_ok);+ ASSERT_TRUE(fence_ok);+ ASSERT_EQ(joined, 0);+ ASSERT_TRUE(freed);+ ASSERT_GT(retained_blocks, before_blocks);+ ASSERT_EQ(after_blocks, before_blocks);+ ASSERT_EQ(after_bytes, before_bytes);+ PASS();+}+TEST(ui_server_oversized_body_rejected) {th_server_t ts;ASSERT_EQ(th_server_start(&ts), 0);@@ -2725,7 +2814,7 @@ TEST(ui_server_delete_project_unlink_failure_keeps_watch) {}static bool ui_health_matches(th_server_t *server, const char *project, const char *status,- const char *indexed_at, bool registered, bool running) {+ const char *indexed_at, bool registered, bool running) {char request[512], response[4096];snprintf(request, sizeof(request), "GET /api/project-health?name=%s HTTP/1.1\r\n\r\n", project);int length = th_http(cbm_http_server_port(server->srv), request, response, sizeof(response));@@ -2744,12 +2833,12 @@ static bool ui_health_matches(th_server_t *server, const char *project, const chyyjson_val *watch = yyjson_obj_get(root, "watch_registered");yyjson_val *loop = yyjson_obj_get(root, "watcher_running");bool matches = yyjson_is_str(actual_status) &&- strcmp(yyjson_get_str(actual_status), status) == 0 &&- yyjson_is_bool(watch) && yyjson_get_bool(watch) == registered &&- yyjson_is_bool(loop) && yyjson_get_bool(loop) == running;+ strcmp(yyjson_get_str(actual_status), status) == 0 && yyjson_is_bool(watch) &&+ yyjson_get_bool(watch) == registered && yyjson_is_bool(loop) &&+ yyjson_get_bool(loop) == running;matches = matches && (indexed_at ? yyjson_is_str(timestamp) &&- strcmp(yyjson_get_str(timestamp), indexed_at) == 0- : yyjson_is_null(timestamp));+ strcmp(yyjson_get_str(timestamp), indexed_at) == 0+ : yyjson_is_null(timestamp));if (strcmp(status, "healthy") == 0) {matches = matches && yyjson_is_int(yyjson_obj_get(root, "nodes")) &&yyjson_get_int(yyjson_obj_get(root, "nodes")) == 0 &&@@ -2785,8 +2874,8 @@ TEST(ui_server_project_health_timestamp_and_no_watcher) {th_server_t server;ASSERT_EQ(th_server_start(&server), 0);- bool healthy = ui_health_matches(&server, "health-indexed", "healthy", project.indexed_at,- false, false);+ bool healthy =+ ui_health_matches(&server, "health-indexed", "healthy", project.indexed_at, false, false);bool missing = ui_health_matches(&server, "health-missing", "missing", NULL, false, false);bool corrupt = ui_health_matches(&server, "health-unreadable", "corrupt", NULL, false, false);th_server_stop(&server);@@ -3236,7 +3325,7 @@ TEST(repo_info_web_base_normalizes_to_https) {/* Never leak credentials into the web base. */ASSERT_NULL(strstr(got, "token"));ASSERT_NULL(strstr(got, "@"));- free(got);+ cbm_free(CBM_MEM_CLASS_OTHER, got);}/* Unrecognized shapes yield NULL, not a bogus link. */ASSERT_NULL(cbm_ui_git_web_base(""));@@ -4005,6 +4094,7 @@ SUITE(httpd) {RUN_TEST(ui_server_free_never_joins_active_index_worker);RUN_TEST(ui_csp_connect_src_has_explicit_download_hosts);RUN_TEST(activity_preserves_severity_and_reports_interrupted_reads);+ RUN_TEST(activity_reply_memory_core_ownership);RUN_TEST(activity_pruned_start_events_do_not_resurrect_on_retry);RUN_TEST(activity_migration_preserves_v1_logs_and_rejects_future_schema);RUN_TEST(activity_log_project_scope_preserves_unknown_v2_history_and_filters_before_limit);@@ -4030,6 +4120,7 @@ SUITE(httpd) {RUN_TEST(ui_server_rpc_rejects_duplicate_adr_arguments);RUN_TEST(ui_server_rpc_allows_only_ui_read_tools);RUN_TEST(ui_server_atlas_routes_are_wired);+ RUN_TEST(ui_server_retained_cache_memory_is_flushed_before_thread_exit);RUN_TEST(ui_server_oversized_body_rejected);RUN_TEST(ui_server_encoded_slash_not_routed);RUN_TEST(ui_server_nul_in_target_rejected);diff --git a/tests/test_runtime_settings.c b/tests/test_runtime_settings.cindex c319c00e3..08f477b60 100644--- a/tests/test_runtime_settings.c+++ b/tests/test_runtime_settings.c@@ -1,4 +1,5 @@#include "test_framework.h"+#include "foundation/mem_core.h"#include "foundation/compat.h"#include "foundation/compat_fs.h"#include "foundation/platform.h"@@ -60,7 +61,7 @@ static yyjson_val *item(yyjson_doc *document, const char *key) {static yyjson_doc *read_snapshot(const char *path) {char *json = cbm_runtime_settings_get_json(path);yyjson_doc *document = json ? yyjson_read(json, strlen(json), 0) : NULL;- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);return document;}static char *apply(const char *path, const char *changes, int *status) {@@ -87,7 +88,7 @@ TEST(runtime_settings_atomic_validation_and_conflict) {char *result =apply(fixture.path, "{\"auto_index\":\"true\",\"CBM_WORKERS\":\"999\"}", &status);ASSERT_EQ(status, 400);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);yyjson_doc *after = read_snapshot(fixture.path);ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(item(after, "auto_index"), "value")), "false");ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_doc_get_root(after), "revision")), revision);@@ -96,13 +97,13 @@ TEST(runtime_settings_atomic_validation_and_conflict) {"{\"auto_index\":\"true\",\"CBM_WORKERS\":\"4\",\"CBM_SQLITE_MMAP_SIZE\":\"0\"}",&status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);char request[256];snprintf(request, sizeof(request),"{\"revision\":\"%s\",\"changes\":{\"auto_index\":\"false\"}}", revision);result = cbm_runtime_settings_apply_json(fixture.path, request, strlen(request), &status);ASSERT_EQ(status, 409);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);cbm_config_t *config = cbm_config_open(fixture.path);ASSERT_TRUE(cbm_config_get_bool(config, "auto_index", false));cbm_config_close(config);@@ -128,7 +129,7 @@ TEST(runtime_settings_strict_allowlist_and_types) {int status = 0;char *result = apply(fixture.path, invalid[i], &status);ASSERT_EQ(status, 400);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);}yyjson_doc *snapshot = read_snapshot(fixture.path);ASSERT_NOT_NULL(snapshot);@@ -151,7 +152,7 @@ TEST(runtime_settings_snapshot_false_mask_reset_and_real_consumer) {"FILE_BYTES\":\"4096\"}",&status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);ASSERT_TRUE(cbm_runtime_settings_init(fixture.path));ASSERT_STR_EQ(cbm_runtime_getenv("CBM_WORKERS"), "4");ASSERT_NULL(cbm_runtime_getenv("CBM_DISABLE_LSP_CROSS"));@@ -162,7 +163,7 @@ TEST(runtime_settings_snapshot_false_mask_reset_and_real_consumer) {ASSERT_STR_EQ(getenv("CBM_DISABLE_LSP_CROSS"), "0");result = apply(fixture.path, "{\"CBM_WORKERS\":\"8\",\"CBM_DISABLE_LSP_CROSS\":null}", &status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);ASSERT_STR_EQ(cbm_runtime_getenv("CBM_WORKERS"), "4");yyjson_doc *snapshot = read_snapshot(fixture.path);ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(item(snapshot, "CBM_WORKERS"), "effective")), "4");@@ -173,7 +174,7 @@ TEST(runtime_settings_snapshot_false_mask_reset_and_real_consumer) {yyjson_doc_free(snapshot);result = apply(fixture.path, "{\"CBM_WORKERS\":null}", &status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);cbm_runtime_settings_reset_for_tests();ASSERT_TRUE(cbm_runtime_settings_init(fixture.path));ASSERT_STR_EQ(cbm_runtime_getenv("CBM_WORKERS"), "2");@@ -193,7 +194,7 @@ TEST(runtime_settings_cli_revision_and_ui_last_writer) {apply(fixture.path,"{\"ui_enabled\":\"true\",\"ui_port\":\"8222\",\"auto_index\":\"true\"}", &status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);cbm_ui_config_t actual;cbm_ui_config_load(&actual);ASSERT_TRUE(actual.ui_enabled);@@ -218,7 +219,7 @@ TEST(runtime_settings_cli_revision_and_ui_last_writer) {ASSERT_EQ(actual.ui_port, 8333);result = apply(fixture.path, "{\"ui_enabled\":null,\"ui_port\":null}", &status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);cbm_ui_config_load(&actual);ASSERT_FALSE(actual.ui_enabled);ASSERT_EQ(actual.ui_port, 8111);@@ -246,7 +247,7 @@ TEST(runtime_settings_sql_failure_rolls_back_whole_batch) {int status = 0;char *result = apply(fixture.path, "{\"auto_index\":\"true\",\"CBM_WORKERS\":\"3\"}", &status);ASSERT_EQ(status, 500);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);yyjson_doc *snapshot = read_snapshot(fixture.path);ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(item(snapshot, "auto_index"), "value")), "false");ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_doc_get_root(snapshot), "revision")), "0");@@ -263,12 +264,12 @@ TEST(runtime_settings_canonical_alias_and_actual_listener) {int status = 0;char *result = apply(alias, "{\"CBM_WORKERS\":\"4\"}", &status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);ASSERT_TRUE(cbm_runtime_settings_init(alias));ASSERT_TRUE(cbm_runtime_settings_init(fixture.path));result = apply(fixture.path, "{\"CBM_WORKERS\":\"8\",\"ui_port\":\"9768\"}", &status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);cbm_runtime_settings_note_http_port(9768);yyjson_doc *snapshot = read_snapshot(fixture.path);ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(item(snapshot, "CBM_WORKERS"), "effective")), "4");@@ -332,7 +333,7 @@ TEST(runtime_settings_preserves_unknown_inherited_values_and_reset) {int status = 0;char *result = apply(fixture.path, "{\"CBM_WORKERS\":\"5\"}", &status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);snapshot = read_snapshot(fixture.path);workers = item(snapshot, "CBM_WORKERS");ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(workers, "value")), "5");@@ -342,7 +343,7 @@ TEST(runtime_settings_preserves_unknown_inherited_values_and_reset) {yyjson_doc_free(snapshot);result = apply(fixture.path, "{\"CBM_WORKERS\":null}", &status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);snapshot = read_snapshot(fixture.path);workers = item(snapshot, "CBM_WORKERS");ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(workers, "value")), "3junk");@@ -353,7 +354,7 @@ TEST(runtime_settings_preserves_unknown_inherited_values_and_reset) {result = apply(fixture.path, "{\"CBM_WORKERS\":\"5\"}", &status);ASSERT_EQ(status, 200);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);cbm_runtime_settings_reset_for_tests();ASSERT_TRUE(cbm_runtime_settings_init(fixture.path));snapshot = read_snapshot(fixture.path);@@ -368,7 +369,36 @@ TEST(runtime_settings_preserves_unknown_inherited_values_and_reset) {PASS();}+TEST(runtime_settings_response_memory_returns_to_caller_baseline) {+ settings_fixture_t fixture;+ ASSERT_TRUE(fixture_open(&fixture));+ size_t blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ size_t bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ for (int request = 0; request < 3; request++) {+ int status = 0;+ char *json;+ if (request == 0)+ json = cbm_runtime_settings_get_json(fixture.path);+ else if (request == 1) {+ json = cbm_runtime_settings_apply_json(fixture.path, "{}", 2, &status);+ ASSERT_EQ(status, 400);+ } else {+ json = apply(fixture.path, "{\"CBM_WORKERS\":\"4\"}", &status);+ ASSERT_EQ(status, 200);+ }+ ASSERT_NOT_NULL(json);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), blocks + 1);+ ASSERT_EQ(cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER), bytes + cbm_mem_usable_size(json));+ cbm_free(CBM_MEM_CLASS_OTHER, json);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), blocks);+ ASSERT_EQ(cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER), bytes);+ }+ fixture_close(&fixture);+ PASS();+}+SUITE(runtime_settings) {+ RUN_TEST(runtime_settings_response_memory_returns_to_caller_baseline);RUN_TEST(runtime_settings_preserves_unknown_inherited_values_and_reset);RUN_TEST(runtime_settings_canonical_alias_and_actual_listener);RUN_TEST(runtime_settings_inherited_clamps_and_unbuilt_features);diff --git a/tests/test_store_arch.c b/tests/test_store_arch.cindex 23ea5c935..4a6d7eb66 100644--- a/tests/test_store_arch.c+++ b/tests/test_store_arch.c@@ -22,6 +22,7 @@*/#include "test_framework.h"#include <store/store.h>+#include "foundation/mem_core.h"#include <string.h>#include <stdlib.h>#include <stdint.h>@@ -1354,7 +1355,7 @@ TEST(louvain_basic) {/* Triangle and pair different */ASSERT_TRUE(comm[1] != comm[4]);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);PASS();}@@ -1363,7 +1364,7 @@ TEST(louvain_empty) {int count = 0;ASSERT_EQ(cbm_louvain(NULL, 0, NULL, 0, &result, &count), CBM_STORE_OK);ASSERT_EQ(count, 0);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);PASS();}@@ -1374,7 +1375,7 @@ TEST(louvain_single_node) {ASSERT_EQ(cbm_louvain(nodes, 1, NULL, 0, &result, &count), CBM_STORE_OK);ASSERT_EQ(count, 1);ASSERT_EQ(result[0].node_id, 42);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);PASS();}@@ -1437,7 +1438,45 @@ TEST(louvain_converges) {}ASSERT_TRUE(same_count >= 8);- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);+ PASS();+}++/* Both the populated graph and isolated-node path return exactly one owned+ * output block. The Louvain compatibility entry point shares this contract. */+TEST(leiden_result_memory_core_ownership) {+ int64_t nodes[] = {1, 2, 3};+ cbm_louvain_edge_t edges[] = {{1, 2}, {2, 3}};+ for (int wrapper = 0; wrapper < 2; wrapper++) {+ for (int connected = 0; connected < 2; connected++) {+ size_t bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ size_t blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ cbm_louvain_result_t *result = NULL;+ int count = 0;+ const cbm_louvain_edge_t *input = connected ? edges : NULL;+ int edge_count = connected ? 2 : 0;+ int rc = wrapper ? cbm_louvain(nodes, 3, input, edge_count, &result, &count)+ : cbm_leiden(nodes, 3, input, edge_count, 1.0, &result, &count);+ ASSERT_EQ(rc, CBM_STORE_OK);+ ASSERT_EQ(count, 3);+ ASSERT_NOT_NULL(result);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), blocks + 1);+ ASSERT_TRUE(cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER) >=+ bytes + 3 * sizeof(*result));+ cbm_free(CBM_MEM_CLASS_OTHER, result);+ ASSERT_EQ(cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER), bytes);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), blocks);+ }+ }+ size_t bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ size_t blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ cbm_louvain_result_t *result = NULL;+ int count = -1;+ ASSERT_EQ(cbm_leiden(NULL, 0, NULL, 0, 1.0, &result, &count), CBM_STORE_OK);+ ASSERT_NULL(result);+ ASSERT_EQ(count, 0);+ ASSERT_EQ(cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER), bytes);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), blocks);PASS();}@@ -1571,7 +1610,7 @@ TEST(leiden_multilevel_collapses_noise) {}ASSERT_TRUE(same >= SZ - 1);}- free(result);+ cbm_free(CBM_MEM_CLASS_OTHER, result);PASS();}@@ -1603,8 +1642,8 @@ TEST(leiden_resolution_controls_granularity) {ASSERT_TRUE(n_hi > n_lo);ASSERT_TRUE(leiden_all_communities_connected(lo, N, edges, ne));ASSERT_TRUE(leiden_all_communities_connected(hi, N, edges, ne));- free(lo);- free(hi);+ cbm_free(CBM_MEM_CLASS_OTHER, lo);+ cbm_free(CBM_MEM_CLASS_OTHER, hi);PASS();}@@ -1874,6 +1913,7 @@ SUITE(store_arch) {RUN_TEST(louvain_empty);RUN_TEST(louvain_single_node);RUN_TEST(louvain_converges);+ RUN_TEST(leiden_result_memory_core_ownership);RUN_TEST(leiden_multilevel_collapses_noise);RUN_TEST(leiden_resolution_controls_granularity);RUN_TEST(arch_clusters_basic);diff --git a/tests/test_subprocess.c b/tests/test_subprocess.cindex 6adee0c01..74fab4555 100644--- a/tests/test_subprocess.c+++ b/tests/test_subprocess.c@@ -15,6 +15,7 @@#include "../src/foundation/platform.h"#include "../src/foundation/compat_fs.h"#include "../src/foundation/git_env.h"+#include "../src/foundation/mem_core.h"#include <errno.h>#include <limits.h>@@ -233,6 +234,43 @@ TEST(subprocess_environment_overrides_preserve_git_isolation) {PASS();}+/* Environment ownership outlives spawn, even if the child already exited.+ * Count while the handle is retained, then release only after terminal poll.+ * This also catches a libc/core mismatch on production mimalloc builds. */+TEST(subprocess_environment_core_ownership) {+ const char *args[] = {cbm_test_program_path, "__cbm_env_values", "CBM_CORE_ENV_TEST", "child",+ NULL};+ const char *overrides[] = {"CBM_CORE_ENV_TEST=first", "CBM_CORE_ENV_TEST=child", NULL};+ cbm_proc_opts_t opts = {.bin = cbm_test_program_path,+ .argv = args,+ .env_overrides = overrides,+ .quiet_timeout_ms = 5000};+ size_t before = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ cbm_subprocess_t *process = NULL;+ int rc = cbm_subprocess_spawn(&opts, &process);+ bool tracked = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER) > before;+ cbm_proc_result_t result = {0};+ cbm_proc_poll_t poll = CBM_PROC_POLL_ERROR;+ if (rc == 0) {+ do {+ poll = cbm_subprocess_poll(process, &result);+ if (poll == CBM_PROC_POLL_RUNNING) {+ cbm_usleep(1000);+ }+ } while (poll == CBM_PROC_POLL_RUNNING);+ }+ if (poll == CBM_PROC_POLL_TERMINAL) {+ cbm_subprocess_destroy(process);+ }+ size_t after = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ ASSERT_EQ(rc, 0);+ ASSERT_EQ(poll, CBM_PROC_POLL_TERMINAL);+ ASSERT_EQ(result.outcome, CBM_PROC_CLEAN);+ ASSERT_TRUE(tracked);+ ASSERT_EQ(after, before);+ PASS();+}+#ifndef _WIN32static cbm_proc_result_t run_sh(const char *script, int quiet_timeout_ms) {const char *argv[] = {"/bin/sh", "-c", script, NULL};@@ -2586,6 +2624,7 @@ SUITE(subprocess) {RUN_TEST(subprocess_classify_timeout_dominates);RUN_TEST(subprocess_outcome_str);RUN_TEST(subprocess_environment_is_child_local);+ RUN_TEST(subprocess_environment_core_ownership);RUN_TEST(subprocess_environment_rejects_invalid_override);RUN_TEST(subprocess_environment_overrides_preserve_git_isolation);#ifndef _WIN32diff --git a/tests/test_ui.c b/tests/test_ui.cindex 9d298c4c8..09829f1a9 100644--- a/tests/test_ui.c+++ b/tests/test_ui.c@@ -13,6 +13,8 @@#include "ui/atlas.h"#include "store/store.h"#include "foundation/subprocess.h"+#include "foundation/mem_core.h"+#include "foundation/platform.h"#include <sqlite3/sqlite3.h>#include <yyjson/yyjson.h>@@ -961,9 +963,9 @@ TEST(layout_regions_two_communities) {ASSERT_NOT_NULL(json2);ASSERT_STR_EQ(json, json2);- free(json2);+ cbm_free(CBM_MEM_CLASS_OTHER, json2);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);cbm_layout_regions_cache_clear();PASS();@@ -989,7 +991,7 @@ TEST(layout_regions_scope_restricts_nodes) {alpha_id = (int)yyjson_get_int(yyjson_obj_get(rv, "id"));}yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);ASSERT_GT(alpha_id, -1);cbm_layout_result_t *r = cbm_layout_compute_region(store, "regions-test", alpha_id, 100);@@ -1167,7 +1169,7 @@ TEST(atlas_tree_aggregates_children) {ASSERT_TRUE(saw_alpha);ASSERT_TRUE(saw_beta);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);cbm_layout_regions_cache_clear();PASS();@@ -1214,13 +1216,13 @@ TEST(atlas_symbol_bundle_totals_and_sections) {"src/beta/b1.c");yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* qn lookup resolves the same node. */char *by_qn =cbm_atlas_symbol_json(store, "regions-test", -1, "regions-test::alpha_one", 10, 0);ASSERT_NOT_NULL(by_qn);- free(by_qn);+ cbm_free(CBM_MEM_CLASS_OTHER, by_qn);/* Unknown symbol → NULL. */ASSERT_NULL(cbm_atlas_symbol_json(store, "regions-test", 999999, NULL, 10, 0));@@ -1260,7 +1262,7 @@ TEST(atlas_flows_walk_and_rank) {}ASSERT_TRUE(alpha_flow);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* Flow detail: coherent DFS structure (parent before child, depths). */char *detail = cbm_atlas_flow_json(store, "regions-test", alpha_flow_id);@@ -1285,7 +1287,7 @@ TEST(atlas_flows_walk_and_rank) {}}yyjson_doc_free(ddoc);- free(detail);+ cbm_free(CBM_MEM_CLASS_OTHER, detail);/* Determinism: fresh cache → byte-identical list. */char *again = NULL;@@ -1294,8 +1296,8 @@ TEST(atlas_flows_walk_and_rank) {ASSERT_NOT_NULL(again);char *first = cbm_atlas_flows_json(store, "regions-test");ASSERT_STR_EQ(again, first);- free(again);- free(first);+ cbm_free(CBM_MEM_CLASS_OTHER, again);+ cbm_free(CBM_MEM_CLASS_OTHER, first);/* Unknown flow id → NULL. */ASSERT_NULL(cbm_atlas_flow_json(store, "regions-test", 9999));@@ -1344,13 +1346,64 @@ TEST(atlas_metrics_totals_and_certainty) {ASSERT_NOT_NULL(yyjson_obj_get(root, "history"));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);cbm_atlas_metrics_cache_clear();cbm_layout_regions_cache_clear();PASS();}+TEST(atlas_response_memory_cache_and_passthrough) {+ cbm_atlas_flows_cache_clear();+ cbm_atlas_metrics_cache_clear();+ cbm_layout_regions_cache_clear();+ cbm_store_t *store = atlas_fixture(NULL);+ ASSERT_NOT_NULL(store);+ /* This fixture exercises graph response caches without retained Git history. */+ ASSERT_EQ(cbm_store_upsert_project(store, "regions-test", ""), CBM_STORE_OK);+ /* Replace any history retained by an earlier metrics test before taking the+ * baseline; clearing response caches alone does not clear history. */+ char *settled = cbm_atlas_metrics_json(store, "regions-test");+ ASSERT_NOT_NULL(settled);+ cbm_free(CBM_MEM_CLASS_OTHER, settled);+ cbm_atlas_metrics_cache_clear();+ cbm_layout_regions_cache_clear();+ size_t before_blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ size_t before_bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ char *(*responses[])(cbm_store_t *, const char *) = {cbm_atlas_metrics_json,+ cbm_atlas_flows_json};+ for (size_t i = 0; i < sizeof(responses) / sizeof(responses[0]); i++) {+ char *cold = responses[i](store, "regions-test");+ ASSERT_NOT_NULL(cold);+ size_t with_cold = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ ASSERT_GT(with_cold, before_blocks);+ char *warm = responses[i](store, "regions-test");+ ASSERT_NOT_NULL(warm);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), with_cold + 1);+ ASSERT_STR_EQ(cold, warm);+ cbm_free(CBM_MEM_CLASS_OTHER, warm);+ cbm_free(CBM_MEM_CLASS_OTHER, cold);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), with_cold - 1);+ }+ cbm_atlas_flows_cache_clear();+ cbm_atlas_metrics_cache_clear();+ cbm_layout_regions_cache_clear();+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), before_blocks);+ ASSERT_EQ(cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER), before_bytes);++ char *input = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, "{");+ ASSERT_NOT_NULL(input);+ char *unchanged = cbm_atlas_attach_observed(store, "regions-test", input);+ ASSERT_TRUE(unchanged == input);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), before_blocks + 1);+ cbm_free(CBM_MEM_CLASS_OTHER, unchanged);+ ASSERT_NULL(cbm_atlas_calloc_array(SIZE_MAX, 2));+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), before_blocks);+ ASSERT_EQ(cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER), before_bytes);+ cbm_store_close(store);+ PASS();+}+TEST(atlas_trace_reachability_calls_and_data) {cbm_layout_regions_cache_clear();cbm_atlas_flows_cache_clear();@@ -1371,7 +1424,7 @@ TEST(atlas_trace_reachability_calls_and_data) {int hops = (int)yyjson_get_int(yyjson_obj_get(root, "hops"));ASSERT_EQ((int)yyjson_arr_size(path), hops + 1);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* beta_three does NOT reach alpha_one (calls point the other way and* the beta cycle never calls into alpha). */@@ -1381,7 +1434,7 @@ TEST(atlas_trace_reachability_calls_and_data) {doc = yyjson_read(json, strlen(json), 0);ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(yyjson_doc_get_root(doc), "reachable")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* Data mode follows only DATA_FLOWS: alpha_two → beta_two works,* alpha_one → beta_two does not (no data edge from alpha_one). */@@ -1394,7 +1447,7 @@ TEST(atlas_trace_reachability_calls_and_data) {ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "reachable")));ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(root, "hops")), 1);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);json = cbm_atlas_trace_json(store, "regions-test", -1, "regions-test::alpha_one", -1,"regions-test::beta_two", "data");@@ -1402,7 +1455,7 @@ TEST(atlas_trace_reachability_calls_and_data) {doc = yyjson_read(json, strlen(json), 0);ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(yyjson_doc_get_root(doc), "reachable")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* Unknown endpoint answers with an error, not a crash. */json = cbm_atlas_trace_json(store, "regions-test", -1, "regions-test::nope", -1,@@ -1411,7 +1464,7 @@ TEST(atlas_trace_reachability_calls_and_data) {doc = yyjson_read(json, strlen(json), 0);ASSERT_NOT_NULL(yyjson_obj_get(yyjson_doc_get_root(doc), "error"));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);cbm_atlas_flows_cache_clear();@@ -1460,7 +1513,7 @@ TEST(atlas_impact_reverse_reachability_and_tests) {yyjson_val *tests = yyjson_obj_get(root, "tests");ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(tests, "count")), 0);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* A test function calling into the beta cycle is reported as a test* to run, with its call distance. */@@ -1512,7 +1565,7 @@ TEST(atlas_impact_reverse_reachability_and_tests) {ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(tnear, 0), "name")), "test_beta");ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(yyjson_arr_get(tnear, 0), "distance")), 3);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* Unknown symbol answers with an error, not a crash. */json = cbm_atlas_impact_json(store, "regions-test", -1, "regions-test::nope");@@ -1520,7 +1573,7 @@ TEST(atlas_impact_reverse_reachability_and_tests) {doc = yyjson_read(json, strlen(json), 0);ASSERT_NOT_NULL(yyjson_obj_get(yyjson_doc_get_root(doc), "error"));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);cbm_atlas_flows_cache_clear();@@ -1556,7 +1609,7 @@ TEST(atlas_symbol_data_flows_and_history_shape) {ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(history, "available")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);cbm_atlas_metrics_cache_clear();cbm_layout_regions_cache_clear();@@ -1589,7 +1642,7 @@ TEST(atlas_scent_buckets_matches_by_region) {ASSERT_EQ(max_count, 3);ASSERT_EQ((int)(bucketed + yyjson_get_int(yyjson_obj_get(root, "unmapped"))), 4);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);json = cbm_atlas_scent_json(store, "regions-test", "_two");ASSERT_NOT_NULL(json);@@ -1598,7 +1651,7 @@ TEST(atlas_scent_buckets_matches_by_region) {ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(root, "total")), 2);ASSERT_EQ((int)yyjson_arr_size(yyjson_obj_get(root, "regions")), 2);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* Sub-2-char queries refuse rather than scan everything. */ASSERT_NULL(cbm_atlas_scent_json(store, "regions-test", "a"));@@ -1628,7 +1681,7 @@ TEST(atlas_bridges_rank_by_region_reach) {* exactly 1 foreign region, so the honest answer is an empty list. */ASSERT_EQ((int)yyjson_arr_size(bridges), 0);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* A third dense community (mirroring the beta pattern: a 3-cycle plus* exactly one inbound cross call) so alpha_one spans TWO foreign@@ -1698,7 +1751,7 @@ TEST(atlas_bridges_rank_by_region_reach) {ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(top, "name")), "alpha_one");ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(top, "regions")), 2);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);cbm_layout_regions_cache_clear();@@ -1757,7 +1810,7 @@ TEST(atlas_symbol_overflow_tail_and_dataflow_presence) {ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "project_has_data_flows")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);cbm_atlas_metrics_cache_clear();cbm_layout_regions_cache_clear();@@ -1792,7 +1845,7 @@ TEST(atlas_blast_buckets_files_by_region) {ASSERT_EQ((int)(bucketed + unmapped), 4);ASSERT_EQ(max_count, 2); /* both alpha files land in one region */yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);ASSERT_NULL(cbm_atlas_blast_json(store, "regions-test", ""));@@ -1819,7 +1872,7 @@ TEST(atlas_handout_is_selfcontained_and_escaped) {ASSERT_NULL(strstr(html, "/Users/"));/* Honest churn: fixture root has no git history → the section says so. */ASSERT_NOT_NULL(strstr(html, "No readable git history"));- free(html);+ cbm_free(CBM_MEM_CLASS_OTHER, html);cbm_store_close(store);cbm_atlas_metrics_cache_clear();@@ -1882,7 +1935,7 @@ TEST(atlas_attach_observed_marks_hops) {yyjson_val *hop2 = yyjson_arr_get(path, 2);ASSERT_NULL(yyjson_obj_get(hop2, "observed"));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* Flow shape: steps with parent indices join the same way. */int64_t alpha_one_id = -1, beta_one_id = -1;@@ -1911,11 +1964,12 @@ TEST(atlas_attach_observed_marks_hops) {snprintf(flow_json, sizeof(flow_json),"{\"steps\":[{\"id\":%lld,\"parent\":-1},{\"id\":%lld,\"parent\":0}]}",(long long)alpha_one_id, (long long)beta_one_id);- char *owned = malloc(strlen(flow_json) + 1);+ size_t before_owned = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ char *owned = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, flow_json);ASSERT_NOT_NULL(owned);- strcpy(owned, flow_json);owned = cbm_atlas_attach_observed(store, "regions-test", owned);ASSERT_NOT_NULL(owned);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), before_owned + 1);doc = yyjson_read(owned, strlen(owned), 0);ASSERT_NOT_NULL(doc);yyjson_val *steps = yyjson_obj_get(yyjson_doc_get_root(doc), "steps");@@ -1924,7 +1978,8 @@ TEST(atlas_attach_observed_marks_hops) {ASSERT_NOT_NULL(obs);ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(obs, "count")), 2);yyjson_doc_free(doc);- free(owned);+ cbm_free(CBM_MEM_CLASS_OTHER, owned);+ ASSERT_EQ(cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER), before_owned);cbm_store_close(store);cbm_atlas_flows_cache_clear();@@ -2016,7 +2071,7 @@ TEST(atlas_who_reports_authorship_evidence) {ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(second, "commits_here")), 1);ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(second, "files_repo_wide")), 1);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* A file with no recorded commits answers honestly, not with an error. */json = cbm_atlas_who_json(store, "who-test", "src/never.c");@@ -2027,7 +2082,7 @@ TEST(atlas_who_reports_authorship_evidence) {ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(jroot, "commits_1y")), 0);ASSERT_EQ((int)yyjson_arr_size(yyjson_obj_get(jroot, "people")), 0);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);cbm_atlas_metrics_cache_clear();@@ -2052,7 +2107,7 @@ TEST(atlas_symbol_history_log_l_and_remote) {yyjson_doc *doc = yyjson_read(json, strlen(json), 0);ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(yyjson_doc_get_root(doc), "available")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(probe);#ifdef _WIN32@@ -2106,7 +2161,7 @@ TEST(atlas_symbol_history_log_l_and_remote) {ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(commit, "author")), "Test");ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(hroot, "truncated")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);(void)th_rmtree(root);PASS();@@ -2148,7 +2203,7 @@ TEST(atlas_repository_map_snapshot_evidence) {ASSERT_NULL(yyjson_obj_get(missing, "strategy"));ASSERT_NULL(yyjson_obj_get(missing, "confidence"));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);PASS();}@@ -2189,19 +2244,77 @@ TEST(atlas_selection_impact_evidence_and_missing_history) {yyjson_get_str(yyjson_obj_get(yyjson_obj_get(root, "snapshot"), "index_revision")),"unknown");yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);json = cbm_atlas_impact_analysis_json(store, "regions-test", "src/new.c", -1, NULL);ASSERT_NOT_NULL(json);doc = yyjson_read(json, strlen(json), 0);ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(yyjson_obj_get(yyjson_doc_get_root(doc), "structural"), "available")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);ASSERT_NULL(cbm_atlas_impact_analysis_json(store, "regions-test", "../private.c", -1, NULL));cbm_store_close(store);PASS();}+TEST(atlas_impact_completed_worker_memory_returns_to_caller_baseline) {+ cbm_atlas_impact_analysis_shutdown();+ char temp[256] = "/tmp/cbm_impact_memory_XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(temp));+ char path[1024];+ snprintf(path, sizeof(path), "%s/index.db", temp);+ cbm_store_t *store = cbm_store_open_path(path);+ ASSERT_NOT_NULL(store);+ ASSERT_EQ(cbm_store_upsert_project(store, "impact-memory", temp), CBM_STORE_OK);+ bool statuses_match = true, cache_matches = true, blocks_match = true, bytes_match = true;+ const char *projects[] = {"impact-memory", "missing-project"};+ const char *expected[] = {"ready", "failed"};+ for (size_t i = 0; i < 2; i++) {+ /* The missing project takes the worker's fallback JSON allocation. */+ void *sentinel = cbm_alloc(CBM_MEM_CLASS_OTHER, 64);+ ASSERT_NOT_NULL(sentinel);+ size_t before_blocks = cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER);+ size_t before_bytes = cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER);+ char *json = NULL;+ bool terminal = false;+ uint64_t deadline = cbm_now_ms() + 15000;+ do {+ json =+ cbm_atlas_impact_analysis_request(store, projects[i], "sample.c", -1, NULL, false);+ yyjson_doc *doc = json ? yyjson_read(json, strlen(json), 0) : NULL;+ const char *status =+ doc ? yyjson_get_str(yyjson_obj_get(yyjson_doc_get_root(doc), "status")) : NULL;+ terminal = status && strcmp(status, expected[i]) == 0;+ bool pending = status && strcmp(status, "pending") == 0;+ yyjson_doc_free(doc);+ if (!pending)+ break;+ cbm_free(CBM_MEM_CLASS_OTHER, json);+ json = NULL;+ cbm_usleep(1000);+ } while (cbm_now_ms() < deadline);+ statuses_match = statuses_match && terminal;+ char *cached = terminal ? cbm_atlas_impact_analysis_request(store, projects[i], "sample.c",+ -1, NULL, false)+ : NULL;+ cache_matches = cache_matches && json && cached && strcmp(json, cached) == 0;+ cbm_free(CBM_MEM_CLASS_OTHER, cached);+ cbm_free(CBM_MEM_CLASS_OTHER, json);+ cbm_atlas_impact_analysis_shutdown(); /* joins and frees the retained worker result */+ blocks_match =+ blocks_match && cbm_mem_class_live_blocks(CBM_MEM_CLASS_OTHER) == before_blocks;+ bytes_match = bytes_match && cbm_mem_class_live_bytes(CBM_MEM_CLASS_OTHER) == before_bytes;+ cbm_free(CBM_MEM_CLASS_OTHER, sentinel);+ }+ cbm_store_close(store);+ th_rmtree(temp);+ ASSERT_TRUE(statuses_match);+ ASSERT_TRUE(cache_matches);+ ASSERT_TRUE(blocks_match);+ ASSERT_TRUE(bytes_match);+ PASS();+}+static bool impact_test_git(const char *root, const char *const *args) {const char *argv[30] = {"git","-C",@@ -2326,9 +2439,9 @@ TEST(atlas_history_ignores_inherited_git_context) {cbm_unsetenv(names[i]);free(saved[i]);}- free(metrics);- free(file);- free(symbol);+ cbm_free(CBM_MEM_CLASS_OTHER, metrics);+ cbm_free(CBM_MEM_CLASS_OTHER, file);+ cbm_free(CBM_MEM_CLASS_OTHER, symbol);cbm_store_close(store);cbm_atlas_metrics_cache_clear();(void)th_rmtree(temp);@@ -2362,8 +2475,8 @@ TEST(atlas_history_remote_urls_strip_credentials_and_force_https) {cbm_atlas_symbol_history_json(store, "atlas-remote-credentials", "sample.c", 1, 3);file_ok[i] = atlas_history_test_remote(file, "https://example.invalid/org/repo");symbol_ok[i] = atlas_history_test_remote(symbol, "https://example.invalid/org/repo");- free(file);- free(symbol);+ cbm_free(CBM_MEM_CLASS_OTHER, file);+ cbm_free(CBM_MEM_CLASS_OTHER, symbol);}cbm_store_close(store);cbm_atlas_metrics_cache_clear();@@ -2429,7 +2542,7 @@ TEST(atlas_selection_impact_git_filters_and_worktree) {ASSERT_EQ(yyjson_get_int(yyjson_obj_get(yyjson_arr_get(co, 0), "shared_commits")), 2);ASSERT_EQ((int)yyjson_arr_size(yyjson_obj_get(yyjson_arr_get(co, 0), "commit_refs")), 2);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);(void)th_rmtree(root);PASS();@@ -2505,7 +2618,7 @@ TEST(atlas_why_extracts_guard_chains) {ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(guards, 1), "cond")), "strict");ASSERT_NULL(yyjson_obj_get(yyjson_arr_get(guards, 1), "negated"));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* delta sits in the ELSE arm: same conditions, innermost negated. */json = cbm_atlas_why_json(store, "why-test", ids[2], NULL, true);@@ -2516,7 +2629,7 @@ TEST(atlas_why_extracts_guard_chains) {ASSERT_EQ((int)yyjson_arr_size(guards), 2);ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(yyjson_arr_get(guards, 1), "negated")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* gamma_fn runs in a loop; downward from alpha lists all three callees* with their guards computed from alpha's own file. */@@ -2526,7 +2639,7 @@ TEST(atlas_why_extracts_guard_chains) {entry = yyjson_arr_get(yyjson_obj_get(yyjson_doc_get_root(doc), "entries"), 0);ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(entry, "loop")));yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);json = cbm_atlas_why_json(store, "why-test", ids[3], NULL, false);ASSERT_NOT_NULL(json);@@ -2535,7 +2648,7 @@ TEST(atlas_why_extracts_guard_chains) {ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root_v, "direction")), "down");ASSERT_EQ((int)yyjson_arr_size(yyjson_obj_get(root_v, "entries")), 3);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);/* Callsite guards helper (the A→B trace hop path). */json = cbm_atlas_callsite_guards_json(store, "why-test", "src/w1.c", 7);@@ -2543,7 +2656,7 @@ TEST(atlas_why_extracts_guard_chains) {doc = yyjson_read(json, strlen(json), 0);ASSERT_EQ((int)yyjson_arr_size(yyjson_obj_get(yyjson_doc_get_root(doc), "guards")), 2);yyjson_doc_free(doc);- free(json);+ cbm_free(CBM_MEM_CLASS_OTHER, json);cbm_store_close(store);th_rmtree(root);@@ -2587,6 +2700,7 @@ SUITE(ui) {RUN_TEST(atlas_symbol_bundle_totals_and_sections);RUN_TEST(atlas_flows_walk_and_rank);RUN_TEST(atlas_metrics_totals_and_certainty);+ RUN_TEST(atlas_response_memory_cache_and_passthrough);RUN_TEST(atlas_trace_reachability_calls_and_data);RUN_TEST(atlas_impact_reverse_reachability_and_tests);RUN_TEST(atlas_symbol_data_flows_and_history_shape);@@ -2602,6 +2716,7 @@ SUITE(ui) {RUN_TEST(atlas_history_remote_urls_strip_credentials_and_force_https);RUN_TEST(atlas_why_extracts_guard_chains);RUN_TEST(atlas_selection_impact_evidence_and_missing_history);+ RUN_TEST(atlas_impact_completed_worker_memory_returns_to_caller_baseline);RUN_TEST(atlas_selection_impact_git_filters_and_worktree);RUN_TEST(atlas_repository_map_snapshot_evidence);}