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
WIP: Algorithmic semantic embeddings + indexing modes (checkpoint before vector storage)
Martin Vogel8a0ad0489b4d
diff --git a/Makefile.cbm b/Makefile.cbmindex c347e6a0d..63adf33b3 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -186,11 +186,15 @@ PIPELINE_SRCS = \src/pipeline/pass_compile_commands.c \src/pipeline/pass_infrascan.c \src/pipeline/pass_k8s.c \- src/pipeline/pass_similarity.c+ src/pipeline/pass_similarity.c \+ src/pipeline/pass_semantic_edges.c# SimHash / MinHash moduleSIMHASH_SRCS = src/simhash/minhash.c+# Semantic embedding module+SEMANTIC_SRCS = src/semantic/semantic.c src/semantic/ast_profile.c+# Traces module (new)TRACES_SRCS = src/traces/traces.c@@ -237,7 +241,7 @@ TRE_CFLAGS = -std=c11 -g -O1 -w -Ivendored/treYYJSON_SRC = vendored/yyjson/yyjson.c# All production sources-PROD_SRCS = $(FOUNDATION_SRCS) $(STORE_SRCS) $(CYPHER_SRCS) $(MCP_SRCS) $(DISCOVER_SRCS) $(GRAPH_BUFFER_SRCS) $(PIPELINE_SRCS) $(SIMHASH_SRCS) $(TRACES_SRCS) $(WATCHER_SRCS) $(CLI_SRCS) $(UI_SRCS) $(YYJSON_SRC)+PROD_SRCS = $(FOUNDATION_SRCS) $(STORE_SRCS) $(CYPHER_SRCS) $(MCP_SRCS) $(DISCOVER_SRCS) $(GRAPH_BUFFER_SRCS) $(PIPELINE_SRCS) $(SIMHASH_SRCS) $(SEMANTIC_SRCS) $(TRACES_SRCS) $(WATCHER_SRCS) $(CLI_SRCS) $(UI_SRCS) $(YYJSON_SRC)EXISTING_C_SRCS = $(EXTRACTION_SRCS) $(LSP_SRCS) $(TS_RUNTIME_SRC) \$(GRAMMAR_SRCS) $(AC_LZ4_SRCS) $(SQLITE_WRITER_SRC)@@ -511,7 +515,7 @@ SYSROOT_FLAG = $(if $(SYSROOT),-isysroot $(SYSROOT),)# Our source files (excluding vendored, grammars, tree-sitter runtime)LINT_SRCS = $(FOUNDATION_SRCS) $(STORE_SRCS) $(CYPHER_SRCS) $(MCP_SRCS) \- $(DISCOVER_SRCS) $(GRAPH_BUFFER_SRCS) $(PIPELINE_SRCS) $(SIMHASH_SRCS) \+ $(DISCOVER_SRCS) $(GRAPH_BUFFER_SRCS) $(PIPELINE_SRCS) $(SIMHASH_SRCS) $(SEMANTIC_SRCS) \$(TRACES_SRCS) $(WATCHER_SRCS) $(CLI_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) \$(SQLITE_WRITER_SRC) $(MAIN_SRC)LINT_HDRS = $(wildcard src/**/*.h src/*.h $(CBM_DIR)/*.h)diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.hindex 8e047ba5f..2e00fbd11 100644--- a/internal/cbm/cbm.h+++ b/internal/cbm/cbm.h@@ -109,6 +109,7 @@ typedef struct {bool is_abstract;bool is_test;bool is_entry_point;+ const char *structural_profile; // AST structural profile (arena-allocated) or NULL} CBMDefinition;/* Argument captured from a call expression */diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.cindex 887c103d9..15c7be7a5 100644--- a/internal/cbm/extract_defs.c+++ b/internal/cbm/extract_defs.c@@ -4,6 +4,7 @@#include "lang_specs.h"#include "foundation/constants.h"#include "simhash/minhash.h"+#include "semantic/ast_profile.h"#include "tree_sitter/api.h" // TSNode, ts_node_*#include <stdint.h> // uint32_t#include <string.h>@@ -50,6 +51,21 @@ static void compute_fingerprint(CBMExtractCtx *ctx, CBMDefinition *def, TSNode fmemcpy(fp, result.values, CBM_MINHASH_K * sizeof(uint32_t));def->fingerprint = fp;def->fingerprint_k = CBM_MINHASH_K;++ /* AST structural profile (signals 8, 9, 11) — rides the same body node */+ cbm_ast_profile_t profile;+ int pc = 0;+ if (def->param_names) {+ while (def->param_names[pc]) {+ pc++;+ }+ }+ if (cbm_ast_profile_compute(body, ctx->source, def->param_names, pc, &profile)) {+ profile.body_lines = (uint16_t)def->lines;+ char sp_buf[CBM_AST_PROFILE_BUF];+ cbm_ast_profile_to_str(&profile, sp_buf, sizeof(sp_buf));+ def->structural_profile = cbm_arena_strdup(ctx->arena, sp_buf);+ }}// Tree-sitter row is 0-based; lines are 1-based.diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex c4073e597..9fb80962a 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -1678,6 +1678,8 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) {cbm_index_mode_t mode = CBM_MODE_FULL;if (mode_str && strcmp(mode_str, "fast") == 0) {mode = CBM_MODE_FAST;+ } else if (mode_str && strcmp(mode_str, "moderate") == 0) {+ mode = CBM_MODE_MODERATE;}free(mode_str);diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.cindex 5929a052f..ed655ad21 100644--- a/src/pipeline/pass_definitions.c+++ b/src/pipeline/pass_definitions.c@@ -21,6 +21,7 @@ enum { PD_RING = 4, PD_RING_MASK = 3, PD_JSON_MARGIN = 10, PD_ESC_MARGIN = 3, PD#include "foundation/compat.h"#include "cbm.h"#include "simhash/minhash.h"+#include "semantic/ast_profile.h"#include <stdio.h>#include <stdlib.h>@@ -200,6 +201,11 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)append_json_string(buf, bufsize, &pos, "fp", fp_hex);}+ /* AST structural profile */+ if (def->structural_profile && pos + CBM_AST_PROFILE_BUF < bufsize) {+ append_json_string(buf, bufsize, &pos, "sp", def->structural_profile);+ }+if (pos < bufsize - SKIP_ONE) {buf[pos] = '}';buf[pos + SKIP_ONE] = '\0';diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.cindex 68843df25..444cca52d 100644--- a/src/pipeline/pass_parallel.c+++ b/src/pipeline/pass_parallel.c@@ -40,6 +40,7 @@ enum {#include "foundation/compat_regex.h"#include "cbm.h"#include "simhash/minhash.h"+#include "semantic/ast_profile.h"#include <stdatomic.h>#include <stdint.h>@@ -223,6 +224,11 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)append_json_string(buf, bufsize, &pos, "fp", fp_hex);}+ /* AST structural profile — append if present and buffer has room. */+ if (def->structural_profile && pos + CBM_AST_PROFILE_BUF < bufsize) {+ append_json_string(buf, bufsize, &pos, "sp", def->structural_profile);+ }+if (pos < bufsize - SKIP_ONE) {buf[pos] = '}';buf[pos + SKIP_ONE] = '\0';diff --git a/src/pipeline/pass_semantic_edges.c b/src/pipeline/pass_semantic_edges.cnew file mode 100644index 000000000..0d81ca91f--- /dev/null+++ b/src/pipeline/pass_semantic_edges.c@@ -0,0 +1,581 @@+/*+ * pass_semantic_edges.c — Emit SEMANTICALLY_RELATED edges from combined+ * algorithmic embeddings (11 signals, zero external dependencies).+ *+ * Runs as a post-pass after pass_similarity. Reads all Function/Method+ * nodes from the graph buffer, computes TF-IDF + Random Indexing + API+ * signatures + type/decorator vectors + AST profile, builds LSH index,+ * scores candidate pairs, applies graph diffusion, emits edges.+ *+ * Runs in moderate and full modes (not fast). Controlled by pipeline mode.+ */+#include "foundation/constants.h"+#include "pipeline/pipeline.h"+#include <stdint.h>+#include "pipeline/pipeline_internal.h"+#include "graph_buffer/graph_buffer.h"+#include "semantic/semantic.h"+#include "semantic/ast_profile.h"+#include "simhash/minhash.h"+#include "foundation/log.h"+#include "foundation/compat.h"+#define XXH_INLINE_ALL+#include "xxhash/xxhash.h"++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++/* ── Helpers ─────────────────────────────────────────────────────── */++enum { PROPS_BUF = 512, MAX_FUNCS_INIT = 4096, GROW = 2, MAX_CALLEES = 64 };++static const char *itoa_log(int val) {+ enum { RING = 4, MASK = 3 };+ static CBM_TLS char bufs[RING][CBM_SZ_32];+ static CBM_TLS int idx = 0;+ int i = idx;+ idx = (idx + SKIP_ONE) & MASK;+ snprintf(bufs[i], sizeof(bufs[i]), "%d", val);+ return bufs[i];+}++static const char *file_ext(const char *path) {+ if (!path) {+ return "";+ }+ const char *dot = strrchr(path, '.');+ return dot ? dot : "";+}++/* Extract a JSON string value by key (simple strstr-based, no full parse). */+static const char *json_str_value(const char *json, const char *key, char *buf, int bufsize) {+ if (!json || !key) {+ return NULL;+ }+ char search[CBM_SZ_64];+ snprintf(search, sizeof(search), "\"%s\":\"", key);+ const char *start = strstr(json, search);+ if (!start) {+ return NULL;+ }+ start += strlen(search);+ const char *end = strchr(start, '"');+ if (!end) {+ return NULL;+ }+ int len = (int)(end - start);+ if (len >= bufsize) {+ len = bufsize - SKIP_ONE;+ }+ memcpy(buf, start, (size_t)len);+ buf[len] = '\0';+ return buf;+}++/* Extract a JSON array of strings by key. Returns count. */+static int json_str_array(const char *json, const char *key, char **out, int max_out) {+ if (!json || !key) {+ return 0;+ }+ char search[CBM_SZ_64];+ snprintf(search, sizeof(search), "\"%s\":[", key);+ const char *start = strstr(json, search);+ if (!start) {+ return 0;+ }+ start += strlen(search);+ int count = 0;+ while (*start && *start != ']' && count < max_out) {+ if (*start == '"') {+ start++;+ const char *end = strchr(start, '"');+ if (!end) {+ break;+ }+ int len = (int)(end - start);+ out[count] = malloc((size_t)len + SKIP_ONE);+ memcpy(out[count], start, (size_t)len);+ out[count][len] = '\0';+ count++;+ start = end + SKIP_ONE;+ } else {+ start++;+ }+ }+ return count;+}++/* ── Tokenize node metadata ──────────────────────────────────────── */++static int tokenize_node(const cbm_gbuf_node_t *n, char **tokens, int max_tokens) {+ int count = 0;+ /* Tokenize name (primary signal) */+ count += cbm_sem_tokenize(n->name, tokens + count, max_tokens - count);+ /* Tokenize qualified name path components */+ if (n->qualified_name && count < max_tokens) {+ count += cbm_sem_tokenize(n->qualified_name, tokens + count, max_tokens - count);+ }+ /* Tokenize file path (directory = domain context) */+ if (n->file_path && count < max_tokens) {+ count += cbm_sem_tokenize(n->file_path, tokens + count, max_tokens - count);+ }+ /* Extract rich metadata from properties_json */+ if (n->properties_json && count < max_tokens) {+ char buf[CBM_SZ_512];+ /* Signature (parameter list text) */+ if (json_str_value(n->properties_json, "signature", buf, sizeof(buf))) {+ count += cbm_sem_tokenize(buf, tokens + count, max_tokens - count);+ }+ /* Return type */+ if (count < max_tokens &&+ json_str_value(n->properties_json, "return_type", buf, sizeof(buf))) {+ count += cbm_sem_tokenize(buf, tokens + count, max_tokens - count);+ }+ /* Docstring (natural language — rich vocabulary for co-occurrence) */+ if (count < max_tokens &&+ json_str_value(n->properties_json, "docstring", buf, sizeof(buf))) {+ count += cbm_sem_tokenize(buf, tokens + count, max_tokens - count);+ }+ /* Param names */+ char *pnames[CBM_SZ_16];+ int pn_count = json_str_array(n->properties_json, "param_names", pnames, CBM_SZ_16);+ for (int p = 0; p < pn_count && count < max_tokens; p++) {+ count += cbm_sem_tokenize(pnames[p], tokens + count, max_tokens - count);+ free(pnames[p]);+ }+ /* Param types */+ char *ptypes[CBM_SZ_16];+ int pt_count = json_str_array(n->properties_json, "param_types", ptypes, CBM_SZ_16);+ for (int p = 0; p < pt_count && count < max_tokens; p++) {+ count += cbm_sem_tokenize(ptypes[p], tokens + count, max_tokens - count);+ free(ptypes[p]);+ }+ /* Decorators */+ char *decos[CBM_SZ_16];+ int dc = json_str_array(n->properties_json, "decorators", decos, CBM_SZ_16);+ for (int p = 0; p < dc && count < max_tokens; p++) {+ count += cbm_sem_tokenize(decos[p], tokens + count, max_tokens - count);+ free(decos[p]);+ }+ }+ return count;+}++/* ── Build per-function semantic data ────────────────────────────── */++static void build_api_vec(const cbm_gbuf_t *gbuf, int64_t node_id, cbm_sem_vec_t *out) {+ memset(out, 0, sizeof(*out));+ const cbm_gbuf_edge_t **edges = NULL;+ int edge_count = 0;+ if (cbm_gbuf_find_edges_by_source_type(gbuf, node_id, "CALLS", &edges, &edge_count) != 0) {+ return;+ }+ int added = 0;+ for (int i = 0; i < edge_count && added < MAX_CALLEES; i++) {+ const cbm_gbuf_node_t *target = cbm_gbuf_find_by_id(gbuf, edges[i]->target_id);+ if (target && target->name) {+ cbm_sem_vec_t callee_ri;+ cbm_sem_random_index(target->name, &callee_ri);+ cbm_sem_vec_add_scaled(out, &callee_ri, 1.0f);+ added++;+ }+ }+ cbm_sem_normalize(out);+}++static void build_type_vec(const char *props_json, cbm_sem_vec_t *out) {+ memset(out, 0, sizeof(*out));+ if (!props_json) {+ return;+ }+ /* Extract param_types and return_type */+ char rt_buf[CBM_SZ_128];+ if (json_str_value(props_json, "return_type", rt_buf, sizeof(rt_buf))) {+ cbm_sem_vec_t ri;+ cbm_sem_random_index(rt_buf, &ri);+ cbm_sem_vec_add_scaled(out, &ri, 1.0f);+ }+ char *ptypes[CBM_SZ_16];+ int pt_count = json_str_array(props_json, "param_types", ptypes, CBM_SZ_16);+ for (int i = 0; i < pt_count; i++) {+ cbm_sem_vec_t ri;+ cbm_sem_random_index(ptypes[i], &ri);+ cbm_sem_vec_add_scaled(out, &ri, 1.0f);+ free(ptypes[i]);+ }+ cbm_sem_normalize(out);+}++static void build_deco_vec(const char *props_json, cbm_sem_vec_t *out) {+ memset(out, 0, sizeof(*out));+ if (!props_json) {+ return;+ }+ char *decos[CBM_SZ_16];+ int dc = json_str_array(props_json, "decorators", decos, CBM_SZ_16);+ for (int i = 0; i < dc; i++) {+ cbm_sem_vec_t ri;+ cbm_sem_random_index(decos[i], &ri);+ cbm_sem_vec_add_scaled(out, &ri, 1.0f);+ free(decos[i]);+ }+ cbm_sem_normalize(out);+}++static void decode_struct_profile(const char *props_json, float *out) {+ memset(out, 0, sizeof(float) * CBM_AST_PROFILE_DIMS);+ if (!props_json) {+ return;+ }+ char sp_buf[CBM_AST_PROFILE_BUF];+ if (json_str_value(props_json, "sp", sp_buf, sizeof(sp_buf))) {+ cbm_ast_profile_t profile;+ if (cbm_ast_profile_from_str(sp_buf, &profile)) {+ cbm_ast_profile_to_vector(&profile, out);+ }+ }+}++static void decode_minhash(const char *props_json, cbm_sem_func_t *func) {+ func->has_minhash = false;+ if (!props_json) {+ return;+ }+ const char *fp_key = strstr(props_json, "\"fp\":\"");+ if (!fp_key) {+ return;+ }+ const char *hex = fp_key + 6; /* strlen("\"fp\":\"") */+ const char *end = strchr(hex, '"');+ if (!end || (int)(end - hex) != CBM_MINHASH_HEX_LEN) {+ return;+ }+ char hex_buf[CBM_MINHASH_HEX_BUF];+ memcpy(hex_buf, hex, CBM_MINHASH_HEX_LEN);+ hex_buf[CBM_MINHASH_HEX_LEN] = '\0';+ cbm_minhash_t mh;+ if (cbm_minhash_from_hex(hex_buf, &mh)) {+ memcpy(func->minhash, mh.values, sizeof(func->minhash));+ func->has_minhash = true;+ }+}++/* ── Pass entry point ────────────────────────────────────────────── */++int cbm_pipeline_pass_semantic_edges(cbm_pipeline_ctx_t *ctx) {+ /* Controlled by pipeline mode (moderate/full), not env var */+ cbm_log_info("pass.start", "pass", "semantic_edges");++ cbm_gbuf_t *gbuf = ctx->gbuf;+ cbm_sem_config_t cfg = cbm_sem_get_config();++ /* Phase 1: Collect all Function/Method nodes */+ const char *labels[] = {"Function", "Method", NULL};+ cbm_sem_func_t *funcs = NULL;+ int func_count = 0;+ int func_cap = 0;++ for (int li = 0; labels[li]; li++) {+ const cbm_gbuf_node_t **nodes = NULL;+ int node_count = 0;+ if (cbm_gbuf_find_by_label(gbuf, labels[li], &nodes, &node_count) != 0) {+ continue;+ }+ for (int i = 0; i < node_count; i++) {+ if (func_count >= func_cap) {+ int new_cap = func_cap < MAX_FUNCS_INIT ? MAX_FUNCS_INIT : func_cap * GROW;+ cbm_sem_func_t *grown = realloc(funcs, (size_t)new_cap * sizeof(cbm_sem_func_t));+ if (!grown) {+ break;+ }+ funcs = grown;+ func_cap = new_cap;+ }+ memset(&funcs[func_count], 0, sizeof(cbm_sem_func_t));+ funcs[func_count].node_id = nodes[i]->id;+ funcs[func_count].file_path = nodes[i]->file_path;+ funcs[func_count].file_ext = file_ext(nodes[i]->file_path);++ /* Decode MinHash and AST profile from properties */+ decode_minhash(nodes[i]->properties_json, &funcs[func_count]);+ decode_struct_profile(nodes[i]->properties_json, funcs[func_count].struct_profile);++ /* Build API, Type, Decorator vectors */+ build_api_vec(gbuf, nodes[i]->id, &funcs[func_count].api_vec);+ build_type_vec(nodes[i]->properties_json, &funcs[func_count].type_vec);+ build_deco_vec(nodes[i]->properties_json, &funcs[func_count].deco_vec);++ func_count++;+ }+ }++ cbm_log_info("pass.semantic.collected", "functions", itoa_log(func_count));++ if (func_count < 2) {+ free(funcs);+ cbm_log_info("pass.done", "pass", "semantic_edges", "edges", "0");+ return 0;+ }++ /* Phase 2+3: Tokenize all nodes + build corpus for IDF + RI */+ cbm_sem_corpus_t *corpus = cbm_sem_corpus_new();+ char **all_tokens = malloc((size_t)func_count * sizeof(char *) * CBM_SEM_MAX_TOKENS);+ int *token_counts = calloc((size_t)func_count, sizeof(int));++ /* Re-iterate nodes for tokenization (indices match funcs[]) */+ int fi = 0;+ for (int li = 0; labels[li]; li++) {+ const cbm_gbuf_node_t **nodes = NULL;+ int node_count = 0;+ if (cbm_gbuf_find_by_label(gbuf, labels[li], &nodes, &node_count) != 0) {+ continue;+ }+ for (int i = 0; i < node_count && fi < func_count; i++, fi++) {+ char *tokens[CBM_SEM_MAX_TOKENS];+ int tc = tokenize_node(nodes[i], tokens, CBM_SEM_MAX_TOKENS);+ token_counts[fi] = tc;++ /* Store token pointers for later TF-IDF/RI vector construction */+ for (int t = 0; t < tc; t++) {+ all_tokens[fi * CBM_SEM_MAX_TOKENS + t] = tokens[t];+ }++ /* Register in corpus */+ cbm_sem_corpus_add_doc(corpus, (const char **)tokens, tc);+ }+ }++ /* Finalize corpus: compute IDF + co-occurrence enriched RI vectors */+ cbm_sem_corpus_finalize(corpus);++ /* Phase 4: Build per-function TF-IDF + RI vectors */+ for (int f = 0; f < func_count; f++) {+ int tc = token_counts[f];+ char **tokens = &all_tokens[f * CBM_SEM_MAX_TOKENS];++ /* TF-IDF: build sparse vector (sorted by token index for merge) */+ /* Simple approach: use token indices from corpus */+ int *indices = malloc((size_t)tc * sizeof(int));+ float *weights = malloc((size_t)tc * sizeof(float));+ int tfidf_len = 0;++ for (int t = 0; t < tc; t++) {+ float idf = cbm_sem_corpus_idf(corpus, tokens[t]);+ if (idf > 0.0f) {+ /* Simple TF = 1 (presence, not frequency — tokens from metadata are short) */+ indices[tfidf_len] = t; /* use sequential index — sorted by construction */+ weights[tfidf_len] = idf;+ tfidf_len++;+ }+ }+ funcs[f].tfidf_indices = indices;+ funcs[f].tfidf_weights = weights;+ funcs[f].tfidf_len = tfidf_len;++ /* RI vector: sum of enriched token vectors */+ memset(&funcs[f].ri_vec, 0, sizeof(cbm_sem_vec_t));+ for (int t = 0; t < tc; t++) {+ const cbm_sem_vec_t *ri = cbm_sem_corpus_ri_vec(corpus, tokens[t]);+ if (ri) {+ float idf = cbm_sem_corpus_idf(corpus, tokens[t]);+ cbm_sem_vec_add_scaled(&funcs[f].ri_vec, ri, idf);+ }+ }+ cbm_sem_normalize(&funcs[f].ri_vec);+ }++ /* Phase 5: Build cosine-LSH index using random hyperplanes on RI vectors.+ * This gives O(n) candidate generation instead of O(n²) brute-force.+ *+ * Method: Generate NUM_HYPERPLANES random d-dim vectors. For each function,+ * compute sign(dot(ri_vec, hyperplane)) for each → a bit signature.+ * Group bits into LSH_BANDS bands of LSH_ROWS bits. Hash each band → bucket.+ * Functions sharing any bucket are candidates. */+ enum {+ NUM_HYPERPLANES = 64,+ SEM_LSH_BANDS = 16,+ SEM_LSH_ROWS = 4,+ SEM_BUCKET_COUNT = 65536,+ SEM_BUCKET_MASK = 65535,+ SEM_BUCKET_CAP_INIT = 16,+ SEM_MAX_CANDIDATES = 200,+ };++ /* Generate deterministic random hyperplanes */+ float hyperplanes[NUM_HYPERPLANES][CBM_SEM_DIM];+ for (int h = 0; h < NUM_HYPERPLANES; h++) {+ for (int d = 0; d < CBM_SEM_DIM; d++) {+ uint64_t seed = XXH3_64bits_withSeed(&d, sizeof(d), (uint64_t)h * CBM_SEM_DIM);+ hyperplanes[h][d] = ((float)(seed & UINT32_MAX) / (float)UINT32_MAX) - 0.5f;+ }+ }++ /* Compute bit signatures for each function */+ uint64_t *signatures = calloc((size_t)func_count, sizeof(uint64_t));+ for (int f = 0; f < func_count; f++) {+ uint64_t sig = 0;+ for (int h = 0; h < NUM_HYPERPLANES; h++) {+ float dot = 0.0f;+ for (int d = 0; d < CBM_SEM_DIM; d++) {+ dot += funcs[f].ri_vec.v[d] * hyperplanes[h][d];+ }+ if (dot > 0.0f) {+ sig |= (1ULL << h);+ }+ }+ signatures[f] = sig;+ }++ /* Build band-based LSH buckets.+ * Each band = SEM_LSH_ROWS consecutive bits → hash to a bucket. */+ typedef struct {+ int *items;+ int count;+ int cap;+ } sem_bucket_t;++ /* Allocate bands × buckets (sparse — only allocate used buckets) */+ sem_bucket_t **band_buckets = calloc(SEM_LSH_BANDS, sizeof(sem_bucket_t *));+ for (int b = 0; b < SEM_LSH_BANDS; b++) {+ band_buckets[b] = calloc(SEM_BUCKET_COUNT, sizeof(sem_bucket_t));+ }++ for (int f = 0; f < func_count; f++) {+ for (int b = 0; b < SEM_LSH_BANDS; b++) {+ /* Extract SEM_LSH_ROWS bits starting at bit b*SEM_LSH_ROWS */+ int shift = b * SEM_LSH_ROWS;+ uint32_t band_val = (uint32_t)((signatures[f] >> shift) & ((1ULL << SEM_LSH_ROWS) - 1));+ /* Hash to bucket (combine band_val with band index for better distribution) */+ uint64_t bh = XXH3_64bits_withSeed(&band_val, sizeof(band_val), (uint64_t)b);+ uint32_t bucket_idx = (uint32_t)(bh & SEM_BUCKET_MASK);+ sem_bucket_t *bucket = &band_buckets[b][bucket_idx];+ if (bucket->count >= bucket->cap) {+ int nc =+ bucket->cap < SEM_BUCKET_CAP_INIT ? SEM_BUCKET_CAP_INIT : bucket->cap * GROW;+ int *ni = realloc(bucket->items, (size_t)nc * sizeof(int));+ if (!ni) {+ continue;+ }+ bucket->items = ni;+ bucket->cap = nc;+ }+ bucket->items[bucket->count++] = f;+ }+ }++ cbm_log_info("pass.semantic.lsh_built", "functions", itoa_log(func_count), "bands",+ itoa_log(SEM_LSH_BANDS));++ /* Phase 6: Query LSH and score candidates.+ * For each function, collect unique candidates from all bands, score, emit edges. */+ int total_edges = 0;+ int *edge_counts = calloc((size_t)func_count, sizeof(int));++ /* Reusable per-query seen set (open addressing on func index) */+ enum { SEEN_CAP = 8192, SEEN_MASK = 8191 };++ for (int i = 0; i < func_count; i++) {+ if (edge_counts[i] >= cfg.max_edges) {+ continue;+ }++ /* Collect unique candidates from all bands */+ int seen[SEEN_CAP];+ memset(seen, -1, sizeof(seen));+ int candidates[SEM_MAX_CANDIDATES];+ int cand_count = 0;++ for (int b = 0; b < SEM_LSH_BANDS && cand_count < SEM_MAX_CANDIDATES; b++) {+ int shift = b * SEM_LSH_ROWS;+ uint32_t band_val = (uint32_t)((signatures[i] >> shift) & ((1ULL << SEM_LSH_ROWS) - 1));+ uint64_t bh = XXH3_64bits_withSeed(&band_val, sizeof(band_val), (uint64_t)b);+ uint32_t bucket_idx = (uint32_t)(bh & SEM_BUCKET_MASK);+ sem_bucket_t *bucket = &band_buckets[b][bucket_idx];++ /* Skip oversized buckets (noise) */+ if (bucket->count > SEM_MAX_CANDIDATES) {+ continue;+ }++ for (int k = 0; k < bucket->count && cand_count < SEM_MAX_CANDIDATES; k++) {+ int j = bucket->items[k];+ if (j <= i) {+ continue; /* only emit A→B where A < B */+ }+ /* Dedup via open-addressing seen set */+ uint32_t slot = (uint32_t)j & SEEN_MASK;+ bool dup = false;+ for (int p = 0; p < SEEN_CAP; p++) {+ uint32_t idx = (slot + (uint32_t)p) & SEEN_MASK;+ if (seen[idx] == -1) {+ seen[idx] = j;+ break;+ }+ if (seen[idx] == j) {+ dup = true;+ break;+ }+ }+ if (dup) {+ continue;+ }+ candidates[cand_count++] = j;+ }+ }++ /* Score candidates */+ for (int c = 0; c < cand_count; c++) {+ int j = candidates[c];+ if (edge_counts[i] >= cfg.max_edges || edge_counts[j] >= cfg.max_edges) {+ continue;+ }+ if (strcmp(funcs[i].file_ext, funcs[j].file_ext) != 0) {+ continue;+ }+ float score = cbm_sem_combined_score(&funcs[i], &funcs[j], &cfg);+ if (score < cfg.threshold) {+ continue;+ }+ bool same_file = funcs[i].file_path && funcs[j].file_path &&+ strcmp(funcs[i].file_path, funcs[j].file_path) == 0;+ char props[PROPS_BUF];+ snprintf(props, sizeof(props), "{\"score\":%.3f,\"same_file\":%s}", score,+ same_file ? "true" : "false");+ cbm_gbuf_insert_edge(gbuf, funcs[i].node_id, funcs[j].node_id, "SEMANTICALLY_RELATED",+ props);+ edge_counts[i]++;+ edge_counts[j]++;+ total_edges++;+ }+ }++ /* Free LSH buckets */+ for (int b = 0; b < SEM_LSH_BANDS; b++) {+ for (int h = 0; h < SEM_BUCKET_COUNT; h++) {+ free(band_buckets[b][h].items);+ }+ free(band_buckets[b]);+ }+ free(band_buckets);+ free(signatures);++ cbm_log_info("pass.done", "pass", "semantic_edges", "edges", itoa_log(total_edges));++ /* Cleanup */+ free(edge_counts);+ for (int f = 0; f < func_count; f++) {+ free(funcs[f].tfidf_indices);+ free(funcs[f].tfidf_weights);+ int tc = token_counts[f];+ for (int t = 0; t < tc; t++) {+ free(all_tokens[f * CBM_SEM_MAX_TOKENS + t]);+ }+ }+ free(all_tokens);+ free(token_counts);+ free(funcs);+ cbm_sem_corpus_free(corpus);++ return 0;+}diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.cindex 5afc3ddc9..5a372db6b 100644--- a/src/pipeline/pipeline.c+++ b/src/pipeline/pipeline.c@@ -157,6 +157,10 @@ atomic_int *cbm_pipeline_cancelled_ptr(cbm_pipeline_t *p) {return p ? &p->cancelled : NULL;}+int cbm_pipeline_get_mode(const cbm_pipeline_t *p) {+ return p ? (int)p->mode : 0;+}+/* Resolve the DB path for this pipeline. Caller must free(). */static char *resolve_db_path(const cbm_pipeline_t *p) {char *path = malloc(CBM_SZ_1K);@@ -425,12 +429,19 @@ static void run_predump_passes(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx) {cbm_log_info("pass.timing", "pass", "route_match", "elapsed_ms",itoa_buf((int)elapsed_ms(t)));}- if (!check_cancel(p)) {+ /* SIMILAR_TO + SEMANTICALLY_RELATED edges only in moderate/full modes */+ if (!check_cancel(p) && p->mode <= CBM_MODE_MODERATE) {cbm_clock_gettime(CLOCK_MONOTONIC, &t);cbm_pipeline_pass_similarity(ctx);cbm_log_info("pass.timing", "pass", "similarity", "elapsed_ms",itoa_buf((int)elapsed_ms(t)));}+ if (!check_cancel(p) && p->mode <= CBM_MODE_MODERATE) {+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_pipeline_pass_semantic_edges(ctx);+ cbm_log_info("pass.timing", "pass", "semantic_edges", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));+ }}/* Run the sequential pipeline path: definitions, k8s, calls, usages, semantic. */@@ -732,6 +743,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {.gbuf = p->gbuf,.registry = p->registry,.cancelled = &p->cancelled,+ .mode = (int)p->mode,};cbm_clock_gettime(CLOCK_MONOTONIC, &t);diff --git a/src/pipeline/pipeline.h b/src/pipeline/pipeline.hindex 9454f9320..84c1f85ec 100644--- a/src/pipeline/pipeline.h+++ b/src/pipeline/pipeline.h@@ -31,8 +31,9 @@ typedef struct cbm_pipeline cbm_pipeline_t;#ifndef CBM_INDEX_MODE_T_DEFINED#define CBM_INDEX_MODE_T_DEFINEDtypedef enum {- CBM_MODE_FULL = 0, /* Full index: read everything, build from scratch */- CBM_MODE_FAST = 1, /* Fast: skip non-essential files (media, docs, etc.) */+ CBM_MODE_FULL = 0, /* Full: everything including SIMILAR_TO + SEMANTICALLY_RELATED */+ CBM_MODE_MODERATE = 1, /* Moderate: fast discovery + SIMILAR_TO + SEMANTICALLY_RELATED */+ CBM_MODE_FAST = 2, /* Fast: skip non-essential files, no similarity/semantic edges */} cbm_index_mode_t;#endif@@ -55,6 +56,9 @@ void cbm_pipeline_cancel(cbm_pipeline_t *p);* owned by the pipeline. Valid until cbm_pipeline_free(). */const char *cbm_pipeline_project_name(const cbm_pipeline_t *p);+/* Get the index mode (CBM_MODE_FULL, CBM_MODE_MODERATE, CBM_MODE_FAST). */+int cbm_pipeline_get_mode(const cbm_pipeline_t *p);+/* ── Index lock (prevents concurrent pipeline runs on same DB) ──── *//* Try to acquire the global index lock. Returns true if acquired,diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.cindex 3978b24af..4294b1976 100644--- a/src/pipeline/pipeline_incremental.c+++ b/src/pipeline/pipeline_incremental.c@@ -243,10 +243,18 @@ static void run_postpasses(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_filcbm_log_info("pass.timing", "pass", "incr_configlink", "elapsed_ms",itoa_buf((int)elapsed_ms(t)));- cbm_clock_gettime(CLOCK_MONOTONIC, &t);- cbm_pipeline_pass_similarity(ctx);- cbm_log_info("pass.timing", "pass", "incr_similarity", "elapsed_ms",- itoa_buf((int)elapsed_ms(t)));+ /* SIMILAR_TO + SEMANTICALLY_RELATED edges only in moderate/full modes */+ if (ctx->mode <= CBM_MODE_MODERATE) {+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_pipeline_pass_similarity(ctx);+ cbm_log_info("pass.timing", "pass", "incr_similarity", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));++ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_pipeline_pass_semantic_edges(ctx);+ cbm_log_info("pass.timing", "pass", "incr_semantic_edges", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));+ }}/* Delete old DB and dump merged graph + hashes to disk. */static void dump_and_persist(cbm_gbuf_t *gbuf, const char *db_path, const char *project,@@ -382,6 +390,7 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil.gbuf = existing,.registry = registry,.cancelled = cbm_pipeline_cancelled_ptr(p),+ .mode = cbm_pipeline_get_mode(p),};for (int i = 0; i < ci; i++) {diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.hindex 868810700..3100c01a3 100644--- a/src/pipeline/pipeline_internal.h+++ b/src/pipeline/pipeline_internal.h@@ -39,6 +39,7 @@ typedef struct {cbm_gbuf_t *gbuf; /* owned by pipeline */cbm_registry_t *registry; /* owned by pipeline */atomic_int *cancelled; /* pointer to pipeline's cancelled flag */+ int mode; /* cbm_index_mode_t (0=full, 1=moderate, 2=fast) *//* Extraction result cache (sequential pipeline optimization).* When non-NULL, pass_definitions stores results here instead of freeing,@@ -353,6 +354,10 @@ int cbm_pipeline_pass_configlink(cbm_pipeline_ctx_t *ctx);/* Pre-dump pass: SIMILAR_TO edges via MinHash fingerprinting. */int cbm_pipeline_pass_similarity(cbm_pipeline_ctx_t *ctx);+/* Pre-dump pass: SEMANTICALLY_RELATED edges via algorithmic embeddings.+ * Opt-in: only runs when CBM_SEMANTIC_ENABLED=1. */+int cbm_pipeline_pass_semantic_edges(cbm_pipeline_ctx_t *ctx);+/* ── Env URL scanner (pass_envscan.c) ────────────────────────────── */typedef struct {diff --git a/src/semantic/ast_profile.c b/src/semantic/ast_profile.cnew file mode 100644index 000000000..ac7733169--- /dev/null+++ b/src/semantic/ast_profile.c@@ -0,0 +1,398 @@+/*+ * ast_profile.c — Extraction-time AST structural signals.+ *+ * Walks a function body AST (alongside MinHash) to compute:+ * Signal 8: Control flow counts, nesting depth, expression types+ * Signal 9: Approximate data flow (params in returns/conditions)+ * Signal 11: Halstead-lite (unique/total operators/operands)+ *+ * Pure functions — thread-safe, no shared state.+ */+#include "semantic/ast_profile.h"+#include "foundation/constants.h"+#include "tree_sitter/api.h"++#include <math.h>+#include <stdio.h>+#include <string.h>++/* ── Node type classification ────────────────────────────────────── */++enum {+ WALK_STACK_CAP = 2048,+ HALSTEAD_SET_SIZE = 512,+ HALSTEAD_SET_MASK = 511,+ PROFILE_FIELD_COUNT = 25,+ DEPTH_SCALE = 10,+};++typedef struct {+ TSNode node;+ int depth;+} profile_frame_t;++static bool is_control_if(const char *k) {+ return strcmp(k, "if_statement") == 0 || strcmp(k, "if_expression") == 0 ||+ strcmp(k, "elif_clause") == 0;+}++static bool is_control_for(const char *k) {+ return strcmp(k, "for_statement") == 0 || strcmp(k, "for_range_loop") == 0 ||+ strcmp(k, "for_expression") == 0 || strcmp(k, "for_in_clause") == 0;+}++static bool is_control_while(const char *k) {+ return strcmp(k, "while_statement") == 0 || strcmp(k, "while_expression") == 0 ||+ strcmp(k, "do_statement") == 0;+}++static bool is_control_switch(const char *k) {+ return strcmp(k, "switch_statement") == 0 || strcmp(k, "switch_expression") == 0 ||+ strcmp(k, "match_expression") == 0 || strcmp(k, "type_switch_statement") == 0;+}++static bool is_control_try(const char *k) {+ return strcmp(k, "try_statement") == 0 || strcmp(k, "try_expression") == 0 ||+ strcmp(k, "catch_clause") == 0 || strcmp(k, "except_clause") == 0;+}++static bool is_return(const char *k) {+ return strcmp(k, "return_statement") == 0 || strcmp(k, "return_expression") == 0;+}++static bool is_comparison(const char *k) {+ return strcmp(k, "binary_expression") == 0 || strcmp(k, "comparison_operator") == 0 ||+ strcmp(k, "boolean_operator") == 0;+}++static bool is_arithmetic(const char *k) {+ return strcmp(k, "unary_expression") == 0 || strcmp(k, "update_expression") == 0;+}++static bool is_assignment(const char *k) {+ return strcmp(k, "assignment_expression") == 0 || strcmp(k, "assignment_statement") == 0 ||+ strcmp(k, "augmented_assignment") == 0 || strcmp(k, "short_var_declaration") == 0;+}++static bool is_string_lit(const char *k) {+ return strcmp(k, "string") == 0 || strcmp(k, "string_literal") == 0 ||+ strcmp(k, "interpreted_string_literal") == 0 || strcmp(k, "raw_string_literal") == 0;+}++static bool is_number_lit(const char *k) {+ return strcmp(k, "number") == 0 || strcmp(k, "integer") == 0 || strcmp(k, "float") == 0 ||+ strcmp(k, "integer_literal") == 0 || strcmp(k, "float_literal") == 0;+}++static bool is_bool_lit(const char *k) {+ return strcmp(k, "true") == 0 || strcmp(k, "false") == 0;+}++static bool is_operator_node(const char *k) {+ /* Named nodes that represent operations (not data). */+ return is_control_if(k) || is_control_for(k) || is_control_while(k) || is_control_switch(k) ||+ is_control_try(k) || is_return(k) || is_comparison(k) || is_arithmetic(k) ||+ is_assignment(k) || strcmp(k, "call_expression") == 0 ||+ strcmp(k, "member_expression") == 0 || strcmp(k, "subscript_expression") == 0;+}++static bool is_identifier(const char *k) {+ return strcmp(k, "identifier") == 0 || strcmp(k, "field_identifier") == 0 ||+ strcmp(k, "property_identifier") == 0 || strcmp(k, "type_identifier") == 0;+}++/* Simple hash set for Halstead unique counting (open addressing). */+static bool halstead_insert(uint32_t *set, const char *key) {+ uint32_t h = 0;+ for (const char *p = key; *p; p++) {+ h = h * 31 + (uint32_t)*p;+ }+ uint32_t idx = h & HALSTEAD_SET_MASK;+ for (int probe = 0; probe < HALSTEAD_SET_SIZE; probe++) {+ uint32_t slot = (idx + (uint32_t)probe) & HALSTEAD_SET_MASK;+ if (set[slot] == 0) {+ set[slot] = h | SKIP_ONE;+ return true; /* new */+ }+ if (set[slot] == (h | SKIP_ONE)) {+ return false; /* existing */+ }+ }+ return false;+}++/* Check if an identifier matches any parameter name. */+static bool is_param_name(const char *ident, const char *source, const char **param_names,+ int param_count) {+ if (!ident || !source || !param_names || param_count == 0) {+ return false;+ }+ for (int i = 0; i < param_count; i++) {+ if (param_names[i] && strcmp(ident, param_names[i]) == 0) {+ return true;+ }+ }+ return false;+}++/* ── Main computation ────────────────────────────────────────────── */++bool cbm_ast_profile_compute(TSNode func_body, const char *source, const char **param_names,+ int param_count, cbm_ast_profile_t *out) {+ if (ts_node_is_null(func_body)) {+ return false;+ }++ memset(out, 0, sizeof(*out));+ out->param_count = (uint16_t)param_count;++ uint32_t op_set[HALSTEAD_SET_SIZE];+ uint32_t operand_set[HALSTEAD_SET_SIZE];+ memset(op_set, 0, sizeof(op_set));+ memset(operand_set, 0, sizeof(operand_set));++ int total_depth = 0;+ int node_count = 0;+ bool in_return = false;+ bool in_condition = false;++ profile_frame_t stack[WALK_STACK_CAP];+ int top = 0;+ stack[top++] = (profile_frame_t){func_body, 0};++ while (top > 0) {+ profile_frame_t frame = stack[--top];+ TSNode node = frame.node;+ int depth = frame.depth;+ uint32_t child_count = ts_node_child_count(node);+ const char *kind = ts_node_type(node);++ if (!ts_node_is_named(node) && child_count == 0) {+ /* Anonymous leaf (punctuation, keywords) — skip. */+ goto push_children;+ }++ node_count++;+ total_depth += depth;++ if ((uint16_t)depth > out->max_nesting_depth) {+ out->max_nesting_depth = (uint16_t)depth;+ }++ /* Signal 8: Control flow */+ if (is_control_if(kind)) {+ out->if_count++;+ }+ if (is_control_for(kind)) {+ out->for_count++;+ }+ if (is_control_while(kind)) {+ out->while_count++;+ }+ if (is_control_switch(kind)) {+ out->switch_count++;+ }+ if (is_control_try(kind)) {+ out->try_count++;+ }+ if (is_return(kind)) {+ out->return_count++;+ in_return = true;+ }++ /* Signal 8: Expression types */+ if (is_comparison(kind)) {+ out->comparison_ops++;+ }+ if (is_arithmetic(kind)) {+ out->arithmetic_ops++;+ }+ if (strcmp(kind, "not_operator") == 0 || strcmp(kind, "boolean_operator") == 0) {+ out->logical_ops++;+ }+ if (is_assignment(kind)) {+ out->assignment_count++;+ out->variable_reassigns++;+ }++ /* Signal 8: Literals */+ if (is_string_lit(kind)) {+ out->string_literals++;+ }+ if (is_number_lit(kind)) {+ out->number_literals++;+ }+ if (is_bool_lit(kind)) {+ out->bool_literals++;+ }++ /* Signal 11: Halstead — operators vs operands */+ if (is_operator_node(kind)) {+ out->total_operators++;+ if (halstead_insert(op_set, kind)) {+ out->unique_operators++;+ }+ }+ if (child_count == 0 && (is_identifier(kind) || is_string_lit(kind) ||+ is_number_lit(kind) || is_bool_lit(kind))) {+ out->total_operands++;+ /* For unique operands, use the node type (normalized) not the text */+ if (halstead_insert(operand_set, kind)) {+ out->unique_operands++;+ }+ out->body_tokens++;+ }++ /* Signal 9: Approximate data flow — track if we're inside a return or condition */+ if (child_count == 0 && is_identifier(kind) && source) {+ uint32_t start = ts_node_start_byte(node);+ uint32_t end = ts_node_end_byte(node);+ if (end > start && (end - start) < CBM_SZ_128) {+ char ident_buf[CBM_SZ_128];+ int ilen = (int)(end - start);+ memcpy(ident_buf, source + start, (size_t)ilen);+ ident_buf[ilen] = '\0';+ if (is_param_name(ident_buf, source, param_names, param_count)) {+ if (in_return) {+ out->params_in_returns++;+ }+ if (in_condition) {+ out->params_in_conditions++;+ }+ }+ }+ }++ /* Track context for data flow: are we inside a condition? */+ if (is_control_if(kind) || is_control_while(kind)) {+ in_condition = true;+ }++ push_children:+ /* Reset context flags when leaving return/condition scope */+ if (is_return(kind)) {+ in_return = false;+ }+ if (child_count > 0 && (is_control_if(kind) || is_control_while(kind))) {+ in_condition = false;+ }++ /* Push children in reverse order */+ for (int i = (int)child_count - SKIP_ONE; i >= 0 && top < WALK_STACK_CAP; i--) {+ stack[top++] = (profile_frame_t){ts_node_child(node, (uint32_t)i), depth + SKIP_ONE};+ }+ }++ /* Compute averages */+ if (node_count > 0) {+ out->avg_nesting_depth_x10 = (uint16_t)((total_depth * DEPTH_SCALE) / node_count);+ }++ return node_count > 0;+}++/* ── Serialization ───────────────────────────────────────────────── */++void cbm_ast_profile_to_str(const cbm_ast_profile_t *p, char *buf, int bufsize) {+ if (!p || !buf || bufsize < SKIP_ONE) {+ if (buf && bufsize > 0) {+ buf[0] = '\0';+ }+ return;+ }+ snprintf(buf, (size_t)bufsize,+ "%u,%u,%u,%u,%u,%u,%u,%u,"+ "%u,%u,%u,%u,"+ "%u,%u,%u,"+ "%u,%u,%u,%u,"+ "%u,%u,%u,%u,"+ "%u,%u",+ p->if_count, p->for_count, p->while_count, p->switch_count, p->try_count,+ p->return_count, p->max_nesting_depth, p->avg_nesting_depth_x10, p->comparison_ops,+ p->arithmetic_ops, p->logical_ops, p->assignment_count, p->string_literals,+ p->number_literals, p->bool_literals, p->param_count, p->params_in_returns,+ p->params_in_conditions, p->variable_reassigns, p->unique_operators,+ p->unique_operands, p->total_operators, p->total_operands, p->body_lines,+ p->body_tokens);+}++bool cbm_ast_profile_from_str(const char *str, cbm_ast_profile_t *out) {+ if (!str || !out) {+ return false;+ }+ memset(out, 0, sizeof(*out));+ unsigned v[PROFILE_FIELD_COUNT];+ int n = sscanf(str,+ "%u,%u,%u,%u,%u,%u,%u,%u,"+ "%u,%u,%u,%u,"+ "%u,%u,%u,"+ "%u,%u,%u,%u,"+ "%u,%u,%u,%u,"+ "%u,%u",+ &v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &v[6], &v[7], &v[8], &v[9], &v[10],+ &v[11], &v[12], &v[13], &v[14], &v[15], &v[16], &v[17], &v[18], &v[19], &v[20],+ &v[21], &v[22], &v[23], &v[24]);+ if (n != PROFILE_FIELD_COUNT) {+ return false;+ }+ out->if_count = (uint16_t)v[0];+ out->for_count = (uint16_t)v[1];+ out->while_count = (uint16_t)v[2];+ out->switch_count = (uint16_t)v[3];+ out->try_count = (uint16_t)v[4];+ out->return_count = (uint16_t)v[5];+ out->max_nesting_depth = (uint16_t)v[6];+ out->avg_nesting_depth_x10 = (uint16_t)v[7];+ out->comparison_ops = (uint16_t)v[8];+ out->arithmetic_ops = (uint16_t)v[9];+ out->logical_ops = (uint16_t)v[10];+ out->assignment_count = (uint16_t)v[11];+ out->string_literals = (uint16_t)v[12];+ out->number_literals = (uint16_t)v[13];+ out->bool_literals = (uint16_t)v[14];+ out->param_count = (uint16_t)v[15];+ out->params_in_returns = (uint16_t)v[16];+ out->params_in_conditions = (uint16_t)v[17];+ out->variable_reassigns = (uint16_t)v[18];+ out->unique_operators = (uint16_t)v[19];+ out->unique_operands = (uint16_t)v[20];+ out->total_operators = (uint16_t)v[21];+ out->total_operands = (uint16_t)v[22];+ out->body_lines = (uint16_t)v[23];+ out->body_tokens = (uint16_t)v[24];+ return true;+}++void cbm_ast_profile_to_vector(const cbm_ast_profile_t *p, float *out) {+ if (!p || !out) {+ return;+ }+ /* Normalize each field to [0,1] range using reasonable maximums. */+ enum { MAX_COUNT = 100, MAX_DEPTH = 20, MAX_HALSTEAD = 200, MAX_TOKENS = 2000 };+ int i = 0;+ out[i++] = (float)p->if_count / MAX_COUNT;+ out[i++] = (float)p->for_count / MAX_COUNT;+ out[i++] = (float)p->while_count / MAX_COUNT;+ out[i++] = (float)p->switch_count / MAX_COUNT;+ out[i++] = (float)p->try_count / MAX_COUNT;+ out[i++] = (float)p->return_count / MAX_COUNT;+ out[i++] = (float)p->max_nesting_depth / MAX_DEPTH;+ out[i++] = (float)p->avg_nesting_depth_x10 / (MAX_DEPTH * DEPTH_SCALE);+ out[i++] = (float)p->comparison_ops / MAX_COUNT;+ out[i++] = (float)p->arithmetic_ops / MAX_COUNT;+ out[i++] = (float)p->logical_ops / MAX_COUNT;+ out[i++] = (float)p->assignment_count / MAX_COUNT;+ out[i++] = (float)p->string_literals / MAX_COUNT;+ out[i++] = (float)p->number_literals / MAX_COUNT;+ out[i++] = (float)p->bool_literals / MAX_COUNT;+ out[i++] = (float)p->param_count / MAX_DEPTH;+ out[i++] = (float)p->params_in_returns / MAX_COUNT;+ out[i++] = (float)p->params_in_conditions / MAX_COUNT;+ out[i++] = (float)p->variable_reassigns / MAX_COUNT;+ out[i++] = (float)p->unique_operators / MAX_HALSTEAD;+ out[i++] = (float)p->unique_operands / MAX_HALSTEAD;+ out[i++] = (float)p->total_operators / MAX_HALSTEAD;+ out[i++] = (float)p->total_operands / MAX_HALSTEAD;+ out[i++] = (float)p->body_lines / MAX_TOKENS;+ out[i++] = (float)p->body_tokens / MAX_TOKENS;+}diff --git a/src/semantic/ast_profile.h b/src/semantic/ast_profile.hnew file mode 100644index 000000000..99fe57524--- /dev/null+++ b/src/semantic/ast_profile.h@@ -0,0 +1,82 @@+/*+ * ast_profile.h — Extraction-time AST structural signals.+ *+ * Computed during the existing AST walk (alongside MinHash) with near-zero+ * marginal cost. Captures control flow shape, expression types, data flow+ * approximations, and Halstead-lite metrics.+ *+ * Stored as a compact comma-separated string in properties_json ("sp" key)+ * and decoded in the semantic post-pass for combined similarity scoring.+ */+#ifndef CBM_AST_PROFILE_H+#define CBM_AST_PROFILE_H++#include <stdbool.h>+#include <stdint.h>++/* Forward declare tree-sitter types to avoid pulling in api.h everywhere. */+typedef struct TSNode TSNode;++/* ── Structural profile: ~27 dimensions ──────────────────────────── */++typedef struct {+ /* Signal 8: Control flow counts */+ uint16_t if_count;+ uint16_t for_count;+ uint16_t while_count;+ uint16_t switch_count;+ uint16_t try_count;+ uint16_t return_count;+ uint16_t max_nesting_depth;+ uint16_t avg_nesting_depth_x10; /* ×10 for fixed-point */++ /* Signal 8: Expression type distribution (counts) */+ uint16_t comparison_ops;+ uint16_t arithmetic_ops;+ uint16_t logical_ops;+ uint16_t assignment_count;++ /* Signal 8: Literal type distribution */+ uint16_t string_literals;+ uint16_t number_literals;+ uint16_t bool_literals;++ /* Signal 9: Approximate data flow */+ uint16_t param_count;+ uint16_t params_in_returns; /* params referenced in return statements */+ uint16_t params_in_conditions; /* params referenced in if conditions */+ uint16_t variable_reassigns; /* same-name assignments */++ /* Signal 11: Halstead-lite */+ uint16_t unique_operators;+ uint16_t unique_operands;+ uint16_t total_operators;+ uint16_t total_operands;++ /* Body metrics */+ uint16_t body_lines;+ uint16_t body_tokens; /* leaf AST node count */+} cbm_ast_profile_t;++/* Number of dimensions when serialized as a float vector. */+enum { CBM_AST_PROFILE_DIMS = 25 };++/* Compute AST structural profile from a function body node.+ * Pure function — thread-safe, no shared state.+ * Returns true if the profile was computed (function was large enough). */+bool cbm_ast_profile_compute(TSNode func_body, const char *source, const char **param_names,+ int param_count, cbm_ast_profile_t *out);++/* Encode profile to a compact comma-separated string.+ * buf must be at least CBM_AST_PROFILE_BUF bytes. */+enum { CBM_AST_PROFILE_BUF = 200 };+void cbm_ast_profile_to_str(const cbm_ast_profile_t *p, char *buf, int bufsize);++/* Decode profile from comma-separated string. Returns true on success. */+bool cbm_ast_profile_from_str(const char *str, cbm_ast_profile_t *out);++/* Convert profile to a normalized float vector for cosine similarity.+ * out must have CBM_AST_PROFILE_DIMS elements. */+void cbm_ast_profile_to_vector(const cbm_ast_profile_t *p, float *out);++#endif /* CBM_AST_PROFILE_H */diff --git a/src/semantic/semantic.c b/src/semantic/semantic.cnew file mode 100644index 000000000..5124c39b1--- /dev/null+++ b/src/semantic/semantic.c@@ -0,0 +1,503 @@+/*+ * semantic.c — Algorithmic code embeddings: TF-IDF, Random Indexing,+ * API/Type/Decorator signatures, combined scoring, graph diffusion.+ *+ * All signals computed from graph buffer metadata — no source file reads.+ * Uses xxHash for deterministic random vectors. Pure C, zero dependencies.+ */+#include "semantic/semantic.h"+#include "foundation/constants.h"+#include "foundation/hash_table.h"+#include "foundation/log.h"+#include "simhash/minhash.h"++#define XXH_INLINE_ALL+#include "xxhash/xxhash.h"++#include <ctype.h>+#include <math.h>+#include <stddef.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++/* ── Constants ───────────────────────────────────────────────────── */++enum {+ TOKEN_BUF_LEN = 128,+ CORPUS_INIT_CAP = 4096,+ DOC_TOKENS_INIT = 64,+ RI_SEED_BASE = 0x52494E44, /* "RIND" */+};++/* ── Configuration ───────────────────────────────────────────────── */++cbm_sem_config_t cbm_sem_get_config(void) {+ cbm_sem_config_t cfg = {+ .w_tfidf = 0.20f,+ .w_ri = 0.25f,+ .w_minhash = 0.10f,+ .w_api = 0.15f,+ .w_type = 0.10f,+ .w_decorator = 0.05f,+ .w_struct_profile = 0.10f,+ .w_dataflow = 0.05f,+ .threshold = (float)CBM_SEM_EDGE_THRESHOLD,+ .max_edges = CBM_SEM_MAX_EDGES,+ };+ const char *thresh = getenv("CBM_SEMANTIC_THRESHOLD");+ if (thresh) {+ float t = (float)atof(thresh);+ if (t > 0.0f && t <= 1.0f) {+ cfg.threshold = t;+ }+ }+ return cfg;+}++bool cbm_sem_is_enabled(void) {+ const char *val = getenv("CBM_SEMANTIC_ENABLED");+ return val && val[0] == '1';+}++/* ── Token extraction ────────────────────────────────────────────── */++int cbm_sem_tokenize(const char *name, char **out, int max_out) {+ if (!name || !out || max_out <= 0) {+ return 0;+ }+ int count = 0;+ char buf[TOKEN_BUF_LEN];+ int blen = 0;++ for (int i = 0; name[i] && count < max_out; i++) {+ char c = name[i];+ /* Split on: dots, slashes, underscores, hyphens, camelCase transitions */+ bool is_split = (c == '.' || c == '/' || c == '_' || c == '-' || c == ' ' || c == '(' ||+ c == ')' || c == ',' || c == ':');+ bool is_camel = (i > 0 && c >= 'A' && c <= 'Z' && name[i - SKIP_ONE] >= 'a' &&+ name[i - SKIP_ONE] <= 'z');++ if (is_split || is_camel) {+ if (blen > 0) {+ buf[blen] = '\0';+ out[count++] = strdup(buf);+ blen = 0;+ }+ if (is_split) {+ continue;+ }+ }+ if (blen < TOKEN_BUF_LEN - SKIP_ONE && isalnum((unsigned char)c)) {+ buf[blen++] = (char)tolower((unsigned char)c);+ }+ }+ if (blen > 0 && count < max_out) {+ buf[blen] = '\0';+ out[count++] = strdup(buf);+ }+ return count;+}++/* ── Dense vector operations ─────────────────────────────────────── */++float cbm_sem_cosine(const cbm_sem_vec_t *a, const cbm_sem_vec_t *b) {+ if (!a || !b) {+ return 0.0f;+ }+ float dot = 0.0f;+ float mag_a = 0.0f;+ float mag_b = 0.0f;+ for (int i = 0; i < CBM_SEM_DIM; i++) {+ dot += a->v[i] * b->v[i];+ mag_a += a->v[i] * a->v[i];+ mag_b += b->v[i] * b->v[i];+ }+ float denom = sqrtf(mag_a) * sqrtf(mag_b);+ if (denom < 1e-10f) {+ return 0.0f;+ }+ return dot / denom;+}++void cbm_sem_random_index(const char *token, cbm_sem_vec_t *out) {+ memset(out, 0, sizeof(*out));+ if (!token) {+ return;+ }+ uint64_t seed = XXH3_64bits(token, strlen(token));+ /* Generate SPARSE_NNZE non-zero entries at deterministic positions */+ for (int i = 0; i < CBM_SEM_SPARSE_NNZE; i++) {+ uint64_t h = XXH3_64bits_withSeed(&i, sizeof(i), seed + RI_SEED_BASE);+ int pos = (int)(h % CBM_SEM_DIM);+ float sign = (h & SKIP_ONE) ? 1.0f : -1.0f;+ out->v[pos] += sign;+ }+}++void cbm_sem_normalize(cbm_sem_vec_t *v) {+ if (!v) {+ return;+ }+ float mag = 0.0f;+ for (int i = 0; i < CBM_SEM_DIM; i++) {+ mag += v->v[i] * v->v[i];+ }+ mag = sqrtf(mag);+ if (mag < 1e-10f) {+ return;+ }+ float inv = 1.0f / mag;+ for (int i = 0; i < CBM_SEM_DIM; i++) {+ v->v[i] *= inv;+ }+}++void cbm_sem_vec_add_scaled(cbm_sem_vec_t *dst, const cbm_sem_vec_t *src, float scale) {+ if (!dst || !src) {+ return;+ }+ for (int i = 0; i < CBM_SEM_DIM; i++) {+ dst->v[i] += scale * src->v[i];+ }+}++/* ── Corpus (IDF + Random Indexing enrichment) ───────────────────── */++typedef struct {+ char *token;+ int doc_freq;+ cbm_sem_vec_t enriched_vec; /* context-enriched via co-occurrence */+} corpus_entry_t;++struct cbm_sem_corpus {+ CBMHashTable *token_map; /* token → index into entries[] */+ corpus_entry_t *entries;+ int entry_count;+ int entry_cap;+ int doc_count;+ bool finalized;++ /* Per-document token lists for co-occurrence pass */+ int **doc_token_ids;+ int *doc_token_counts;+ int doc_cap;+};++static int corpus_get_or_add(cbm_sem_corpus_t *c, const char *token) {+ char idx_buf[CBM_SZ_16];+ const char *existing = cbm_ht_get(c->token_map, token);+ if (existing) {+ return atoi(existing);+ }+ if (c->entry_count >= c->entry_cap) {+ int new_cap = c->entry_cap < CORPUS_INIT_CAP ? CORPUS_INIT_CAP : c->entry_cap * 2;+ corpus_entry_t *grown = realloc(c->entries, (size_t)new_cap * sizeof(corpus_entry_t));+ if (!grown) {+ return -1;+ }+ c->entries = grown;+ c->entry_cap = new_cap;+ }+ int idx = c->entry_count++;+ c->entries[idx].token = strdup(token);+ c->entries[idx].doc_freq = 0;+ memset(&c->entries[idx].enriched_vec, 0, sizeof(cbm_sem_vec_t));+ snprintf(idx_buf, sizeof(idx_buf), "%d", idx);+ cbm_ht_set(c->token_map, strdup(token), strdup(idx_buf));+ return idx;+}++cbm_sem_corpus_t *cbm_sem_corpus_new(void) {+ cbm_sem_corpus_t *c = calloc(SKIP_ONE, sizeof(cbm_sem_corpus_t));+ if (c) {+ c->token_map = cbm_ht_create(CORPUS_INIT_CAP);+ }+ return c;+}++void cbm_sem_corpus_add_doc(cbm_sem_corpus_t *corpus, const char **tokens, int count) {+ if (!corpus || !tokens || count <= 0) {+ return;+ }+ /* Track document for co-occurrence pass */+ if (corpus->doc_count >= corpus->doc_cap) {+ int new_cap = corpus->doc_cap < DOC_TOKENS_INIT ? DOC_TOKENS_INIT : corpus->doc_cap * 2;+ corpus->doc_token_ids = realloc(corpus->doc_token_ids, (size_t)new_cap * sizeof(int *));+ corpus->doc_token_counts = realloc(corpus->doc_token_counts, (size_t)new_cap * sizeof(int));+ corpus->doc_cap = new_cap;+ }+ int doc_idx = corpus->doc_count++;+ corpus->doc_token_ids[doc_idx] = malloc((size_t)count * sizeof(int));+ corpus->doc_token_counts[doc_idx] = count;++ /* Per-doc unique set for IDF */+ int *seen = calloc((size_t)corpus->entry_cap + (size_t)count + CORPUS_INIT_CAP, sizeof(int));+ int seen_count = 0;++ for (int i = 0; i < count; i++) {+ int tid = corpus_get_or_add(corpus, tokens[i]);+ corpus->doc_token_ids[doc_idx][i] = tid;+ if (tid < 0) {+ continue;+ }+ /* Check uniqueness for IDF (simple linear scan — tokens per doc is small) */+ bool is_new = true;+ for (int j = 0; j < seen_count; j++) {+ if (seen[j] == tid) {+ is_new = false;+ break;+ }+ }+ if (is_new) {+ seen[seen_count++] = tid;+ corpus->entries[tid].doc_freq++;+ }+ }+ free(seen);+}++void cbm_sem_corpus_finalize(cbm_sem_corpus_t *corpus) {+ if (!corpus || corpus->finalized) {+ return;+ }++ /* Initialize base random index vectors for each token */+ for (int i = 0; i < corpus->entry_count; i++) {+ cbm_sem_random_index(corpus->entries[i].token, &corpus->entries[i].enriched_vec);+ }++ /* Co-occurrence pass: for each document, accumulate neighbor vectors */+ for (int d = 0; d < corpus->doc_count; d++) {+ int *ids = corpus->doc_token_ids[d];+ int len = corpus->doc_token_counts[d];+ for (int i = 0; i < len; i++) {+ if (ids[i] < 0) {+ continue;+ }+ cbm_sem_vec_t *target = &corpus->entries[ids[i]].enriched_vec;+ /* Add neighbor vectors within window */+ for (int w = -CBM_SEM_WINDOW; w <= CBM_SEM_WINDOW; w++) {+ if (w == 0) {+ continue;+ }+ int j = i + w;+ if (j < 0 || j >= len || ids[j] < 0) {+ continue;+ }+ float weight = 1.0f / (float)abs(w); /* closer = more influence */+ cbm_sem_vec_t neighbor_ri;+ cbm_sem_random_index(corpus->entries[ids[j]].token, &neighbor_ri);+ cbm_sem_vec_add_scaled(target, &neighbor_ri, weight);+ }+ }+ }++ /* Normalize all enriched vectors */+ for (int i = 0; i < corpus->entry_count; i++) {+ cbm_sem_normalize(&corpus->entries[i].enriched_vec);+ }++ corpus->finalized = true;+}++float cbm_sem_corpus_idf(const cbm_sem_corpus_t *corpus, const char *token) {+ if (!corpus || !token || corpus->doc_count == 0) {+ return 0.0f;+ }+ const char *idx_str = cbm_ht_get(corpus->token_map, token);+ if (!idx_str) {+ return 0.0f;+ }+ int idx = atoi(idx_str);+ if (idx < 0 || idx >= corpus->entry_count) {+ return 0.0f;+ }+ int df = corpus->entries[idx].doc_freq;+ if (df <= 0) {+ return 0.0f;+ }+ return logf((float)corpus->doc_count / (float)df);+}++const cbm_sem_vec_t *cbm_sem_corpus_ri_vec(const cbm_sem_corpus_t *corpus, const char *token) {+ if (!corpus || !token) {+ return NULL;+ }+ const char *idx_str = cbm_ht_get(corpus->token_map, token);+ if (!idx_str) {+ return NULL;+ }+ int idx = atoi(idx_str);+ if (idx < 0 || idx >= corpus->entry_count) {+ return NULL;+ }+ return &corpus->entries[idx].enriched_vec;+}++int cbm_sem_corpus_doc_count(const cbm_sem_corpus_t *corpus) {+ return corpus ? corpus->doc_count : 0;+}++void cbm_sem_corpus_free(cbm_sem_corpus_t *corpus) {+ if (!corpus) {+ return;+ }+ for (int i = 0; i < corpus->entry_count; i++) {+ free(corpus->entries[i].token);+ }+ free(corpus->entries);+ for (int d = 0; d < corpus->doc_count; d++) {+ free(corpus->doc_token_ids[d]);+ }+ free(corpus->doc_token_ids);+ free(corpus->doc_token_counts);+ if (corpus->token_map) {+ cbm_ht_free(corpus->token_map);+ }+ free(corpus);+}++/* ── Combined scoring ────────────────────────────────────────────── */++float cbm_sem_proximity(const char *path_a, const char *path_b) {+ if (!path_a || !path_b) {+ return 1.0f;+ }+ /* Count shared directory components */+ int shared = 0;+ int total_a = 0;+ int total_b = 0;+ const char *a = path_a;+ const char *b = path_b;+ while (*a && *b && *a == *b) {+ if (*a == '/') {+ shared++;+ }+ a++;+ b++;+ }+ for (const char *p = path_a; *p; p++) {+ if (*p == '/') {+ total_a++;+ }+ }+ for (const char *p = path_b; *p; p++) {+ if (*p == '/') {+ total_b++;+ }+ }+ int max_total = total_a > total_b ? total_a : total_b;+ if (max_total == 0) {+ return 1.0f;+ }+ float ratio = (float)shared / (float)max_total;+ /* Same file = 1.10, same dir = 1.05, distant = 1.00 */+ return 1.0f + ratio * 0.10f;+}++/* Cosine similarity for small float arrays (AST profile). */+static float small_cosine(const float *a, const float *b, int dims) {+ float dot = 0.0f;+ float ma = 0.0f;+ float mb = 0.0f;+ for (int i = 0; i < dims; i++) {+ dot += a[i] * b[i];+ ma += a[i] * a[i];+ mb += b[i] * b[i];+ }+ float denom = sqrtf(ma) * sqrtf(mb);+ return denom < 1e-10f ? 0.0f : dot / denom;+}++float cbm_sem_combined_score(const cbm_sem_func_t *a, const cbm_sem_func_t *b,+ const cbm_sem_config_t *cfg) {+ if (!a || !b || !cfg) {+ return 0.0f;+ }+ float score = 0.0f;++ /* Signal 1: TF-IDF sparse cosine */+ if (a->tfidf_len > 0 && b->tfidf_len > 0) {+ float dot = 0.0f;+ float ma = 0.0f;+ float mb = 0.0f;+ /* Sparse dot product: O(a_len + b_len) via merge */+ int ia = 0;+ int ib = 0;+ while (ia < a->tfidf_len && ib < b->tfidf_len) {+ if (a->tfidf_indices[ia] == b->tfidf_indices[ib]) {+ dot += a->tfidf_weights[ia] * b->tfidf_weights[ib];+ ia++;+ ib++;+ } else if (a->tfidf_indices[ia] < b->tfidf_indices[ib]) {+ ia++;+ } else {+ ib++;+ }+ }+ for (int i = 0; i < a->tfidf_len; i++) {+ ma += a->tfidf_weights[i] * a->tfidf_weights[i];+ }+ for (int i = 0; i < b->tfidf_len; i++) {+ mb += b->tfidf_weights[i] * b->tfidf_weights[i];+ }+ float denom = sqrtf(ma) * sqrtf(mb);+ if (denom > 1e-10f) {+ score += cfg->w_tfidf * (dot / denom);+ }+ }++ /* Signal 2: Random Indexing */+ score += cfg->w_ri * cbm_sem_cosine(&a->ri_vec, &b->ri_vec);++ /* Signal 3: MinHash Jaccard */+ if (a->has_minhash && b->has_minhash) {+ double j = cbm_minhash_jaccard((const cbm_minhash_t *)a->minhash,+ (const cbm_minhash_t *)b->minhash);+ score += cfg->w_minhash * (float)j;+ }++ /* Signal 4: API Signatures */+ score += cfg->w_api * cbm_sem_cosine(&a->api_vec, &b->api_vec);++ /* Signal 5: Type Signatures */+ score += cfg->w_type * cbm_sem_cosine(&a->type_vec, &b->type_vec);++ /* Signal 7: Decorator Pattern */+ score += cfg->w_decorator * cbm_sem_cosine(&a->deco_vec, &b->deco_vec);++ /* Signal 8+9+11: Structural profile + data flow + Halstead */+ enum { SP_DIMS = 25 };+ float sp_score = small_cosine(a->struct_profile, b->struct_profile, SP_DIMS);+ score += cfg->w_struct_profile * sp_score;++ /* Signal 6: Module proximity (multiplier, not additive) */+ score *= cbm_sem_proximity(a->file_path, b->file_path);++ return score;+}++/* ── Graph diffusion ─────────────────────────────────────────────── */++void cbm_sem_diffuse(cbm_sem_vec_t *combined, const cbm_sem_vec_t *neighbors, int neighbor_count,+ float alpha) {+ if (!combined || !neighbors || neighbor_count <= 0) {+ return;+ }+ /* Blend: combined = (1-α) × combined + α × mean(neighbors) */+ cbm_sem_vec_t mean;+ memset(&mean, 0, sizeof(mean));+ for (int n = 0; n < neighbor_count; n++) {+ for (int i = 0; i < CBM_SEM_DIM; i++) {+ mean.v[i] += neighbors[n].v[i];+ }+ }+ float inv_n = 1.0f / (float)neighbor_count;+ float one_minus_alpha = 1.0f - alpha;+ for (int i = 0; i < CBM_SEM_DIM; i++) {+ combined->v[i] = (one_minus_alpha * combined->v[i]) + (alpha * mean.v[i] * inv_n);+ }+ cbm_sem_normalize(combined);+}diff --git a/src/semantic/semantic.h b/src/semantic/semantic.hnew file mode 100644index 000000000..acf756762--- /dev/null+++ b/src/semantic/semantic.h@@ -0,0 +1,169 @@+/*+ * semantic.h — Algorithmic code embeddings for SEMANTICALLY_RELATED edges.+ *+ * Combines 11 signals into a unified similarity score without external+ * models or dependencies. All signals derived from graph buffer metadata+ * and the existing AST walk.+ *+ * Signals:+ * 1. TF-IDF on metadata tokens (vocabulary overlap)+ * 2. Random Indexing with co-occurrence (within-codebase synonym bridging)+ * 3. MinHash structural (existing, decoded from "fp" property)+ * 4. API Signature vectors (same callees → related)+ * 5. Type Signature vectors (same param/return types → related)+ * 6. Module Proximity (same directory → boost)+ * 7. Decorator Pattern vectors (same annotations → related)+ * 8. AST Structural Profile (control flow shape, expression types)+ * 9. Approximate Data Flow (params→return, params→condition)+ * 10. Graph Diffusion (transitive closure via neighbor blending)+ * 11. Halstead-Lite (operator/operand complexity profile)+ *+ * Note: signals 8, 9, 11 are computed at extraction time (ast_profile.h)+ * and stored in properties_json. The rest are computed in the post-pass.+ */+#ifndef CBM_SEMANTIC_H+#define CBM_SEMANTIC_H++#include <stdbool.h>+#include <stdint.h>++/* ── Configuration ───────────────────────────────────────────────── */++/* Random Indexing dimension. 256 is sufficient for <500K functions. */+enum { CBM_SEM_DIM = 256 };++/* Random Indexing: non-zero entries per sparse random vector. */+enum { CBM_SEM_SPARSE_NNZE = 8 };++/* Co-occurrence window half-width. */+enum { CBM_SEM_WINDOW = 5 };++/* Default score threshold for SEMANTICALLY_RELATED edge emission.+ * 0.75 balances recall with precision: validated ~95% precision on+ * Linux kernel (0.80 = 100% but only 90 edges, 0.70 = 2047 edges+ * but ~80% precision). */+#define CBM_SEM_EDGE_THRESHOLD 0.75++/* Maximum SEMANTICALLY_RELATED edges per node. */+enum { CBM_SEM_MAX_EDGES = 10 };++/* Signal weights (sum to ~1.0, proximity is a multiplier). */+typedef struct {+ float w_tfidf;+ float w_ri;+ float w_minhash;+ float w_api;+ float w_type;+ float w_decorator;+ float w_struct_profile;+ float w_dataflow;+ float threshold;+ int max_edges;+} cbm_sem_config_t;++/* Get default config (can be overridden via env vars). */+cbm_sem_config_t cbm_sem_get_config(void);++/* Check if semantic embeddings are enabled (CBM_SEMANTIC_ENABLED=1). */+bool cbm_sem_is_enabled(void);++/* ── Token extraction ────────────────────────────────────────────── */++/* Maximum tokens per function from metadata (name + qn + path + sig + docstring + params). */+enum { CBM_SEM_MAX_TOKENS = 512 };++/* Split a name into tokens: camelCase, snake_case, dot.separated.+ * Writes up to max_out tokens into out. Returns token count.+ * Tokens are lowercased. Caller must free each token. */+int cbm_sem_tokenize(const char *name, char **out, int max_out);++/* ── Dense vectors ───────────────────────────────────────────────── */++/* A fixed-size dense vector for cosine similarity. */+typedef struct {+ float v[CBM_SEM_DIM];+} cbm_sem_vec_t;++/* Compute cosine similarity between two dense vectors. */+float cbm_sem_cosine(const cbm_sem_vec_t *a, const cbm_sem_vec_t *b);++/* Generate a deterministic sparse random vector for a token.+ * Uses xxHash(token) as seed. Output has SEM_SPARSE_NNZE non-zeros. */+void cbm_sem_random_index(const char *token, cbm_sem_vec_t *out);++/* Normalize a vector to unit length in-place. */+void cbm_sem_normalize(cbm_sem_vec_t *v);++/* Add src to dst: dst[i] += scale * src[i]. */+void cbm_sem_vec_add_scaled(cbm_sem_vec_t *dst, const cbm_sem_vec_t *src, float scale);++/* ── Per-function semantic data ──────────────────────────────────── */++/* All computed signals for one function. */+typedef struct {+ int64_t node_id;+ const char *file_path;+ const char *file_ext;++ /* Sparse TF-IDF: stored as parallel arrays of (token_index, weight). */+ int *tfidf_indices;+ float *tfidf_weights;+ int tfidf_len;++ /* Dense vectors for RI, API, Type, Decorator. */+ cbm_sem_vec_t ri_vec;+ cbm_sem_vec_t api_vec;+ cbm_sem_vec_t type_vec;+ cbm_sem_vec_t deco_vec;++ /* AST profile as float vector (decoded from "sp" property). */+ float struct_profile[25];++ /* MinHash fingerprint (decoded from "fp" property). */+ bool has_minhash;+ uint32_t minhash[64];+} cbm_sem_func_t;++/* ── Corpus-level data ───────────────────────────────────────────── */++/* Opaque corpus handle for IDF and Random Indexing state. */+typedef struct cbm_sem_corpus cbm_sem_corpus_t;++/* Create a new corpus from function data. */+cbm_sem_corpus_t *cbm_sem_corpus_new(void);++/* Register a function's tokens in the corpus (for IDF counting). */+void cbm_sem_corpus_add_doc(cbm_sem_corpus_t *corpus, const char **tokens, int count);++/* Finalize: compute IDF, build enriched token vectors via co-occurrence. */+void cbm_sem_corpus_finalize(cbm_sem_corpus_t *corpus);++/* Get IDF weight for a token. Returns 0.0 for unknown tokens. */+float cbm_sem_corpus_idf(const cbm_sem_corpus_t *corpus, const char *token);++/* Get the enriched Random Indexing vector for a token (after co-occurrence). */+const cbm_sem_vec_t *cbm_sem_corpus_ri_vec(const cbm_sem_corpus_t *corpus, const char *token);++/* Get the total document count. */+int cbm_sem_corpus_doc_count(const cbm_sem_corpus_t *corpus);++/* Free corpus. */+void cbm_sem_corpus_free(cbm_sem_corpus_t *corpus);++/* ── Combined scoring ────────────────────────────────────────────── */++/* Compute combined similarity score between two functions. */+float cbm_sem_combined_score(const cbm_sem_func_t *a, const cbm_sem_func_t *b,+ const cbm_sem_config_t *cfg);++/* Module proximity multiplier based on file paths. */+float cbm_sem_proximity(const char *path_a, const char *path_b);++/* ── Graph diffusion ─────────────────────────────────────────────── */++/* Apply one iteration of graph diffusion to a combined embedding.+ * Blends with mean of top-k neighbor embeddings (α=0.3). */+void cbm_sem_diffuse(cbm_sem_vec_t *combined, const cbm_sem_vec_t *neighbors, int neighbor_count,+ float alpha);++#endif /* CBM_SEMANTIC_H */