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
Add MinHash fingerprinting and SIMILAR_TO edges for near-clone detection
Martin Vogel452f5a7b1f82
diff --git a/Makefile.cbm b/Makefile.cbmindex b2e95b461..c347e6a0d 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -186,6 +186,10 @@ PIPELINE_SRCS = \src/pipeline/pass_compile_commands.c \src/pipeline/pass_infrascan.c \src/pipeline/pass_k8s.c \+ src/pipeline/pass_similarity.c++# SimHash / MinHash module+SIMHASH_SRCS = src/simhash/minhash.c# Traces module (new)TRACES_SRCS = src/traces/traces.c@@ -233,7 +237,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) $(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) $(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)@@ -301,7 +305,9 @@ TEST_SECURITY_SRCS = tests/test_security.cTEST_YAML_SRCS = tests/test_yaml.c-ALL_TEST_SRCS = $(TEST_FOUNDATION_SRCS) $(TEST_EXTRACTION_SRCS) $(TEST_STORE_SRCS) $(TEST_CYPHER_SRCS) $(TEST_MCP_SRCS) $(TEST_DISCOVER_SRCS) $(TEST_GRAPH_BUFFER_SRCS) $(TEST_PIPELINE_SRCS) $(TEST_WATCHER_SRCS) $(TEST_LZ4_SRCS) $(TEST_SQLITE_WRITER_SRCS) $(TEST_GO_LSP_SRCS) $(TEST_C_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_INTEGRATION_SRCS)+TEST_SIMHASH_SRCS = tests/test_simhash.c++ALL_TEST_SRCS = $(TEST_FOUNDATION_SRCS) $(TEST_EXTRACTION_SRCS) $(TEST_STORE_SRCS) $(TEST_CYPHER_SRCS) $(TEST_MCP_SRCS) $(TEST_DISCOVER_SRCS) $(TEST_GRAPH_BUFFER_SRCS) $(TEST_PIPELINE_SRCS) $(TEST_WATCHER_SRCS) $(TEST_LZ4_SRCS) $(TEST_SQLITE_WRITER_SRCS) $(TEST_GO_LSP_SRCS) $(TEST_C_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_SIMHASH_SRCS) $(TEST_INTEGRATION_SRCS)# ── Build directories ────────────────────────────────────────────@@ -505,8 +511,8 @@ 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) $(TRACES_SRCS) \- $(WATCHER_SRCS) $(CLI_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) \+ $(DISCOVER_SRCS) $(GRAPH_BUFFER_SRCS) $(PIPELINE_SRCS) $(SIMHASH_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)LINT_TEST_SRCS = $(ALL_TEST_SRCS)diff --git a/README.md b/README.mdindex 71cea408f..22656b13c 100644--- a/README.md+++ b/README.md@@ -339,6 +339,19 @@ codebase-memory-mcp config set auto_index_limit 50000 # max files for auto-incodebase-memory-mcp config reset auto_index # reset to default```+### Environment Variables++| Variable | Default | Description |+|----------|---------|-------------|+| `CBM_CACHE_DIR` | `~/.cache/codebase-memory-mcp` | Override the database storage directory. All project indexes and config are stored here. |+| `CBM_DIAGNOSTICS` | `false` | Set to `1` or `true` to enable periodic diagnostics output to `/tmp/cbm-diagnostics-<pid>.json`. |+| `CBM_DOWNLOAD_URL` | *(GitHub releases)* | Override the download URL for updates. Used for testing or self-hosted deployments. |++```bash+# Store indexes in a custom directory+export CBM_CACHE_DIR=~/my-projects/cbm-data+```+## Custom File ExtensionsMap additional file extensions to supported languages via JSON config files. Useful for framework-specific extensions like `.blade.php` (Laravel) or `.mjs` (ES modules).diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.hindex 56876a49e..8e047ba5f 100644--- a/internal/cbm/cbm.h+++ b/internal/cbm/cbm.h@@ -103,6 +103,8 @@ typedef struct {const char *route_method; // HTTP method from decorator (e.g., "POST") or NULLint complexity; // cyclomatic complexityint lines; // body line count+ uint32_t *fingerprint; // MinHash fingerprint (arena-allocated, K values) or NULL+ int fingerprint_k; // number of hash values (CBM_MINHASH_K or 0)bool is_exported;bool is_abstract;bool is_test;diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.cindex 96cc8b4a7..e4c0b4dc5 100644--- a/internal/cbm/extract_defs.c+++ b/internal/cbm/extract_defs.c@@ -3,6 +3,7 @@#include "helpers.h"#include "lang_specs.h"#include "foundation/constants.h"+#include "simhash/minhash.h"#include "tree_sitter/api.h" // TSNode, ts_node_*#include <stdint.h> // uint32_t#include <string.h>@@ -28,6 +29,30 @@ enum {NESTED_CLASS_STACK_CAP = 128,};+/* Compute MinHash fingerprint for a function body node and store in def.+ * Sets def->fingerprint (arena-allocated) and def->fingerprint_k on success,+ * leaves them NULL/0 if the body is too short. */+static void compute_fingerprint(CBMExtractCtx *ctx, CBMDefinition *def, TSNode func_node) {+ /* Find the function body child */+ TSNode body = ts_node_child_by_field_name(func_node, TS_FIELD("body"));+ if (ts_node_is_null(body)) {+ /* Some languages use "block" or the function itself as the body */+ body = func_node;+ }+ cbm_minhash_t result;+ if (!cbm_minhash_compute(body, ctx->source, (int)ctx->language, &result)) {+ return; /* Too short or empty — no fingerprint */+ }+ /* Arena-allocate the fingerprint array */+ uint32_t *fp = cbm_arena_alloc(ctx->arena, CBM_MINHASH_K * sizeof(uint32_t));+ if (!fp) {+ return;+ }+ memcpy(fp, result.values, CBM_MINHASH_K * sizeof(uint32_t));+ def->fingerprint = fp;+ def->fingerprint_k = CBM_MINHASH_K;+}+// Tree-sitter row is 0-based; lines are 1-based.// Null-terminated array allocation: need count + 1 for terminator.@@ -1421,6 +1446,9 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpecdef.complexity = cbm_count_branching(node, spec->branching_node_types);}+ // MinHash fingerprint+ compute_fingerprint(ctx, &def, func_node);+// JS/TS export detectionif (ctx->language == CBM_LANG_JAVASCRIPT || ctx->language == CBM_LANG_TYPESCRIPT ||ctx->language == CBM_LANG_TSX) {@@ -1855,6 +1883,9 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, const char *class_def.complexity = cbm_count_branching(child, spec->branching_node_types);}+ // MinHash fingerprint+ compute_fingerprint(ctx, &def, child);+cbm_defs_push(&ctx->result->defs, a, def);}@@ -1988,6 +2019,9 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpecdef.complexity = cbm_count_branching(child, spec->branching_node_types);}+ // MinHash fingerprint+ compute_fingerprint(ctx, &def, child);+cbm_defs_push(&ctx->result->defs, a, def);}}diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.cindex acf61e0d6..5929a052f 100644--- a/src/pipeline/pass_definitions.c+++ b/src/pipeline/pass_definitions.c@@ -20,6 +20,7 @@ enum { PD_RING = 4, PD_RING_MASK = 3, PD_JSON_MARGIN = 10, PD_ESC_MARGIN = 3, PD#include "foundation/log.h"#include "foundation/compat.h"#include "cbm.h"+#include "simhash/minhash.h"#include <stdio.h>#include <stdlib.h>@@ -191,6 +192,14 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)append_json_string(buf, bufsize, &pos, "route_path", def->route_path);append_json_string(buf, bufsize, &pos, "route_method", def->route_method);+ /* MinHash fingerprint — append if present and buffer has room. */+ if (def->fingerprint && def->fingerprint_k > 0 &&+ pos + CBM_MINHASH_HEX_LEN + CBM_MINHASH_JSON_OVERHEAD < bufsize) {+ char fp_hex[CBM_MINHASH_HEX_BUF];+ cbm_minhash_to_hex((const cbm_minhash_t *)def->fingerprint, fp_hex, sizeof(fp_hex));+ append_json_string(buf, bufsize, &pos, "fp", fp_hex);+ }+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 825233af1..68843df25 100644--- a/src/pipeline/pass_parallel.c+++ b/src/pipeline/pass_parallel.c@@ -39,6 +39,7 @@ enum {#include "foundation/mem.h"#include "foundation/compat_regex.h"#include "cbm.h"+#include "simhash/minhash.h"#include <stdatomic.h>#include <stdint.h>@@ -212,6 +213,16 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)append_json_str_array(buf, bufsize, &pos, "param_types", def->param_types);append_json_string(buf, bufsize, &pos, "route_path", def->route_path);append_json_string(buf, bufsize, &pos, "route_method", def->route_method);++ /* MinHash fingerprint — append if present and buffer has room.+ * Hex-encoded K=64 uint32 = 512 chars + key/quotes ≈ 520 chars. */+ if (def->fingerprint && def->fingerprint_k > 0 &&+ pos + CBM_MINHASH_HEX_LEN + CBM_MINHASH_JSON_OVERHEAD < bufsize) {+ char fp_hex[CBM_MINHASH_HEX_BUF];+ cbm_minhash_to_hex((const cbm_minhash_t *)def->fingerprint, fp_hex, sizeof(fp_hex));+ append_json_string(buf, bufsize, &pos, "fp", fp_hex);+ }+if (pos < bufsize - SKIP_ONE) {buf[pos] = '}';buf[pos + SKIP_ONE] = '\0';diff --git a/src/pipeline/pass_similarity.c b/src/pipeline/pass_similarity.cnew file mode 100644index 000000000..2d5c3c538--- /dev/null+++ b/src/pipeline/pass_similarity.c@@ -0,0 +1,220 @@+/*+ * pass_similarity.c — Generate SIMILAR_TO edges from MinHash fingerprints.+ *+ * Reads "fp" hex strings from Function/Method node properties,+ * builds an LSH index, and emits SIMILAR_TO edges for pairs with+ * Jaccard similarity ≥ threshold.+ *+ * Runs as a post-pass after enrichment (both full and incremental).+ */+#include "foundation/constants.h"+#include "pipeline/pipeline.h"+#include <stdint.h>+#include "pipeline/pipeline_internal.h"+#include "graph_buffer/graph_buffer.h"+#include "simhash/minhash.h"+#include "foundation/log.h"+#include "foundation/compat.h"++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++enum { FP_KEY_PREFIX_LEN = 6, MIN_FP_ENTRIES = 2 }; /* strlen("\"fp\":\"") */++/* ── Helpers ─────────────────────────────────────────────────────── */++/* Extract file extension from a path (including the dot). */+static const char *file_ext(const char *path) {+ if (!path) {+ return "";+ }+ const char *dot = strrchr(path, '.');+ return dot ? dot : "";+}++/* Parse "fp" hex string from a node's properties_json.+ * Returns true if found and decoded successfully. */+static bool parse_fp_from_props(const char *props_json, cbm_minhash_t *out) {+ if (!props_json) {+ return false;+ }+ const char *fp_key = strstr(props_json, "\"fp\":\"");+ if (!fp_key) {+ return false;+ }+ const char *hex_start = fp_key + FP_KEY_PREFIX_LEN;+ /* Find closing quote */+ const char *hex_end = strchr(hex_start, '"');+ if (!hex_end) {+ return false;+ }+ int hex_len = (int)(hex_end - hex_start);+ if (hex_len != CBM_MINHASH_HEX_LEN) {+ return false;+ }+ char hex_buf[CBM_MINHASH_HEX_BUF];+ memcpy(hex_buf, hex_start, (size_t)hex_len);+ hex_buf[hex_len] = '\0';+ return cbm_minhash_from_hex(hex_buf, out);+}++/* Log helper for integer-to-string in log calls. */+static const char *itoa_log(int val) {+ enum { RING_BUF_COUNT = 4, RING_BUF_MASK = 3 };+ static CBM_TLS char bufs[RING_BUF_COUNT][CBM_SZ_32];+ static CBM_TLS int idx = 0;+ int i = idx;+ idx = (idx + SKIP_ONE) & RING_BUF_MASK;+ snprintf(bufs[i], sizeof(bufs[i]), "%d", val);+ return bufs[i];+}++/* ── Internal types ──────────────────────────────────────────────── */++enum { FP_ENTRY_INIT_CAP = 256, FP_ENTRY_GROW = 2, PROPS_BUF_LEN = 256 };++typedef struct {+ int64_t node_id;+ cbm_minhash_t fp;+ const char *file_path;+ const char *ext;+} fp_entry_t;++/* Collect all Function/Method nodes with fingerprints from graph buffer. */+static int collect_fp_entries(cbm_gbuf_t *gbuf, fp_entry_t **out_entries) {+ fp_entry_t *entries = NULL;+ int count = 0;+ int cap = 0;++ const char *labels[] = {"Function", "Method", NULL};+ 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++) {+ const cbm_gbuf_node_t *n = nodes[i];+ cbm_minhash_t fp;+ if (!parse_fp_from_props(n->properties_json, &fp)) {+ continue;+ }+ if (count >= cap) {+ int new_cap = cap < FP_ENTRY_INIT_CAP ? FP_ENTRY_INIT_CAP : cap * FP_ENTRY_GROW;+ fp_entry_t *grown = realloc(entries, (size_t)new_cap * sizeof(fp_entry_t));+ if (!grown) {+ break;+ }+ entries = grown;+ cap = new_cap;+ }+ entries[count++] = (fp_entry_t){+ .node_id = n->id,+ .fp = fp,+ .file_path = n->file_path,+ .ext = file_ext(n->file_path),+ };+ }+ }+ *out_entries = entries;+ return count;+}++/* Emit SIMILAR_TO edges for one source entry against LSH candidates. */+static int emit_edges_for_entry(cbm_gbuf_t *gbuf, const fp_entry_t *src,+ const cbm_lsh_entry_t **candidates, int cand_count,+ int edge_count) {+ int emitted = 0;+ for (int c = 0; c < cand_count; c++) {+ const cbm_lsh_entry_t *cand = candidates[c];+ if (cand->node_id == src->node_id) {+ continue;+ }+ if (strcmp(src->ext, cand->file_ext) != 0) {+ continue;+ }+ if (src->node_id >= cand->node_id) {+ continue;+ }+ if (edge_count + emitted >= CBM_MINHASH_MAX_EDGES_PER_NODE) {+ break;+ }+ double jaccard = cbm_minhash_jaccard(&src->fp, cand->fingerprint);+ if (jaccard < CBM_MINHASH_JACCARD_THRESHOLD) {+ continue;+ }+ bool same_file =+ src->file_path && cand->file_path && strcmp(src->file_path, cand->file_path) == 0;+ char props[PROPS_BUF_LEN];+ snprintf(props, sizeof(props), "{\"jaccard\":%.3f,\"same_file\":%s}", jaccard,+ same_file ? "true" : "false");+ cbm_gbuf_insert_edge(gbuf, src->node_id, cand->node_id, "SIMILAR_TO", props);+ emitted++;+ }+ return emitted;+}++/* ── Pass entry point ────────────────────────────────────────────── */++int cbm_pipeline_pass_similarity(cbm_pipeline_ctx_t *ctx) {+ cbm_log_info("pass.start", "pass", "similarity");++ cbm_gbuf_t *gbuf = ctx->gbuf;++ fp_entry_t *entries = NULL;+ int entry_count = collect_fp_entries(gbuf, &entries);++ cbm_log_info("pass.similarity.collected", "nodes_with_fp", itoa_log(entry_count));++ if (entry_count < MIN_FP_ENTRIES) {+ free(entries);+ cbm_log_info("pass.done", "pass", "similarity", "edges", "0");+ return 0;+ }++ /* Build LSH index */+ cbm_lsh_index_t *lsh = cbm_lsh_new();+ cbm_lsh_entry_t *lsh_entries = malloc((size_t)entry_count * sizeof(cbm_lsh_entry_t));+ if (!lsh_entries) {+ free(entries);+ cbm_lsh_free(lsh);+ return CBM_NOT_FOUND;+ }++ for (int i = 0; i < entry_count; i++) {+ lsh_entries[i] = (cbm_lsh_entry_t){+ .node_id = entries[i].node_id,+ .fingerprint = &entries[i].fp,+ .file_path = entries[i].file_path,+ .file_ext = entries[i].ext,+ };+ cbm_lsh_insert(lsh, &lsh_entries[i]);+ }++ /* Query and emit edges */+ int *edge_counts = calloc((size_t)entry_count, sizeof(int));+ int total_edges = 0;++ for (int i = 0; i < entry_count; i++) {+ if (edge_counts[i] >= CBM_MINHASH_MAX_EDGES_PER_NODE) {+ continue;+ }+ const cbm_lsh_entry_t **candidates = NULL;+ int cand_count = 0;+ cbm_lsh_query(lsh, &entries[i].fp, &candidates, &cand_count);++ int emitted =+ emit_edges_for_entry(gbuf, &entries[i], candidates, cand_count, edge_counts[i]);+ edge_counts[i] += emitted;+ total_edges += emitted;+ }++ cbm_log_info("pass.done", "pass", "similarity", "edges", itoa_log(total_edges));++ free(edge_counts);+ free(lsh_entries);+ free(entries);+ cbm_lsh_free(lsh);+ return 0;+}diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.cindex b78322921..5afc3ddc9 100644--- a/src/pipeline/pipeline.c+++ b/src/pipeline/pipeline.c@@ -425,6 +425,12 @@ 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)) {+ 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)));+ }}/* Run the sequential pipeline path: definitions, k8s, calls, usages, semantic. */diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.cindex f520506c6..3978b24af 100644--- a/src/pipeline/pipeline_incremental.c+++ b/src/pipeline/pipeline_incremental.c@@ -242,6 +242,11 @@ static void run_postpasses(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_filcbm_pipeline_pass_configlink(ctx);cbm_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)));}/* 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,diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.hindex 2fa4f4338..868810700 100644--- a/src/pipeline/pipeline_internal.h+++ b/src/pipeline/pipeline_internal.h@@ -350,6 +350,9 @@ int cbm_pipeline_pass_decorator_tags(cbm_gbuf_t *gbuf, const char *project);/* Pre-dump pass: config ↔ code linking. */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);+/* ── Env URL scanner (pass_envscan.c) ────────────────────────────── */typedef struct {diff --git a/src/simhash/minhash.c b/src/simhash/minhash.cnew file mode 100644index 000000000..549d828da--- /dev/null+++ b/src/simhash/minhash.c@@ -0,0 +1,378 @@+/*+ * minhash.c — MinHash fingerprinting + LSH for near-clone detection.+ *+ * Computes K=64 MinHash signatures from normalised AST node-type+ * trigrams. Uses xxHash with distinct seeds for each permutation.+ * Pure functions — thread-safe, no shared state.+ *+ * LSH index uses b=32 bands × r=2 rows for candidate generation.+ */+#include "simhash/minhash.h"+#include "foundation/constants.h"+#include "foundation/log.h"+/* Inline all xxHash functions — avoids separate compilation unit. */+#define XXH_INLINE_ALL+#include "xxhash/xxhash.h"+#include "tree_sitter/api.h"++#include <stddef.h>+#include <stdint.h>+#include <stdlib.h>+#include <string.h>+#include <stdio.h>+#include <ctype.h>++/* ── AST node type normalisation ─────────────────────────────────── */++/* Maximum trigram string length: 3 node types × max 40 chars each + separators */+enum { TRIGRAM_BUF_LEN = 160 };++/* Maximum AST body nodes to walk (stack depth). */+enum { AST_WALK_CAP = 2048 };++/* Hex encoding constants */+enum { HEX_CHARS_PER_U32 = 8, HEX_BASE = 16 };++/* Trigram window and minimum threshold */+enum { TRIGRAM_WINDOW = 2, MIN_TRIGRAM_COUNT = 3 };++/* Hash truncation mask (uint64 → uint32) */+enum { U32_MASK = 0xFFFFFFFF };++/* Dynamic array growth constants */+enum { BUCKET_INIT_CAP = 8, GROW_FACTOR = 2, ENTRY_INIT_CAP = 64, RESULT_INIT_CAP = 64 };++/* Maximum normalised tokens per function body. */+enum { MAX_TOKENS = 4096 };++/* Check if a node type is an identifier-like leaf. */+static bool is_identifier_type(const char *kind) {+ return strcmp(kind, "identifier") == 0 || strcmp(kind, "field_identifier") == 0 ||+ strcmp(kind, "property_identifier") == 0 || strcmp(kind, "type_identifier") == 0 ||+ strcmp(kind, "shorthand_property_identifier") == 0 ||+ strcmp(kind, "shorthand_field_identifier") == 0 || strcmp(kind, "variable_name") == 0 ||+ strcmp(kind, "name") == 0;+}++/* Check if a node type is a string literal. */+static bool is_string_type(const char *kind) {+ return strcmp(kind, "string") == 0 || strcmp(kind, "string_literal") == 0 ||+ strcmp(kind, "interpreted_string_literal") == 0 ||+ strcmp(kind, "raw_string_literal") == 0 || strcmp(kind, "template_string") == 0 ||+ strcmp(kind, "string_content") == 0 || strcmp(kind, "escape_sequence") == 0;+}++/* Check if a node type is a number literal. */+static bool is_number_type(const char *kind) {+ return strcmp(kind, "number") == 0 || strcmp(kind, "integer") == 0 ||+ strcmp(kind, "float") == 0 || strcmp(kind, "integer_literal") == 0 ||+ strcmp(kind, "float_literal") == 0 || strcmp(kind, "int_literal") == 0 ||+ strcmp(kind, "number_literal") == 0;+}++/* Check if a node type is a type annotation. */+static bool is_type_annotation(const char *kind) {+ return strcmp(kind, "type_identifier") == 0 || strcmp(kind, "predefined_type") == 0 ||+ strcmp(kind, "primitive_type") == 0 || strcmp(kind, "builtin_type") == 0 ||+ strcmp(kind, "type_annotation") == 0 || strcmp(kind, "simple_type") == 0;+}++/* Normalise a node type string. Returns a short canonical string+ * or the original kind if no normalisation applies. */+static const char *normalise_node_type(const char *kind) {+ if (is_identifier_type(kind)) {+ return "I";+ }+ if (is_string_type(kind)) {+ return "S";+ }+ if (is_number_type(kind)) {+ return "N";+ }+ if (is_type_annotation(kind)) {+ return "T";+ }+ return kind;+}++/* ── MinHash computation ─────────────────────────────────────────── */++/* Phase 1: Walk AST iteratively and collect normalised token types. */+static int collect_ast_tokens(TSNode root, const char **tokens, int max_tokens) {+ int token_count = 0;+ TSNode stack[AST_WALK_CAP];+ int top = 0;+ stack[top++] = root;++ while (top > 0 && token_count < max_tokens) {+ TSNode node = stack[--top];+ uint32_t child_count = ts_node_child_count(node);+ const char *kind = ts_node_type(node);++ if (child_count == 0) {+ if (kind[0] != '\0') {+ tokens[token_count++] = normalise_node_type(kind);+ }+ } else {+ if (kind[0] != '\0' && ts_node_is_named(node)) {+ tokens[token_count++] = normalise_node_type(kind);+ }+ for (int i = (int)child_count - SKIP_ONE; i >= 0 && top < AST_WALK_CAP; i--) {+ stack[top++] = ts_node_child(node, (uint32_t)i);+ }+ }+ }+ return token_count;+}++/* Phase 2: Hash trigrams from token sequence into MinHash signature. */+static int hash_trigrams(const char **tokens, int token_count, cbm_minhash_t *out) {+ for (int k = 0; k < CBM_MINHASH_K; k++) {+ out->values[k] = UINT32_MAX;+ }++ char trigram_buf[TRIGRAM_BUF_LEN];+ int trigram_count = 0;++ for (int i = 0; i + TRIGRAM_WINDOW < token_count; i++) {+ int len = snprintf(trigram_buf, sizeof(trigram_buf), "%s|%s|%s", tokens[i], tokens[i + 1],+ tokens[i + 2]);+ if (len <= 0 || (size_t)len >= sizeof(trigram_buf)) {+ continue;+ }+ trigram_count++;+ for (int k = 0; k < CBM_MINHASH_K; k++) {+ uint64_t h = XXH3_64bits_withSeed(trigram_buf, (size_t)len, (uint64_t)k);+ uint32_t h32 = (uint32_t)(h & U32_MASK);+ if (h32 < out->values[k]) {+ out->values[k] = h32;+ }+ }+ }+ return trigram_count;+}++bool cbm_minhash_compute(TSNode func_body, const char *source, int language, cbm_minhash_t *out) {+ (void)source;+ (void)language;++ if (ts_node_is_null(func_body)) {+ return false;+ }++ const char *tokens[MAX_TOKENS];+ int token_count = collect_ast_tokens(func_body, tokens, MAX_TOKENS);+ if (token_count < CBM_MINHASH_MIN_NODES) {+ return false;+ }++ int trigram_count = hash_trigrams(tokens, token_count, out);+ return trigram_count >= MIN_TRIGRAM_COUNT;+}++/* ── Jaccard similarity ──────────────────────────────────────────── */++double cbm_minhash_jaccard(const cbm_minhash_t *a, const cbm_minhash_t *b) {+ if (!a || !b) {+ return 0.0;+ }+ int matching = 0;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ if (a->values[i] == b->values[i]) {+ matching++;+ }+ }+ return (double)matching / (double)CBM_MINHASH_K;+}++/* ── Hex encoding/decoding ───────────────────────────────────────── */++void cbm_minhash_to_hex(const cbm_minhash_t *fp, char *buf, int bufsize) {+ if (!fp || !buf || bufsize < CBM_MINHASH_HEX_BUF) {+ if (buf && bufsize > 0) {+ buf[0] = '\0';+ }+ return;+ }+ int pos = 0;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ pos += snprintf(buf + pos, (size_t)(bufsize - pos), "%08x", fp->values[i]);+ }+}++bool cbm_minhash_from_hex(const char *hex, cbm_minhash_t *out) {+ if (!hex || !out) {+ return false;+ }+ size_t len = strlen(hex);+ if ((int)len != CBM_MINHASH_HEX_LEN) {+ return false;+ }+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ char chunk[HEX_CHARS_PER_U32 + SKIP_ONE];+ ptrdiff_t offset = (ptrdiff_t)i * HEX_CHARS_PER_U32;+ memcpy(chunk, hex + offset, HEX_CHARS_PER_U32);+ chunk[HEX_CHARS_PER_U32] = '\0';+ unsigned long val = strtoul(chunk, NULL, HEX_BASE);+ out->values[i] = (uint32_t)val;+ }+ return true;+}++/* ── LSH index ───────────────────────────────────────────────────── */++/* Each band bucket is a dynamic array of entry indices (not pointers —+ * the entries array may be reallocated during insert, invalidating ptrs). */+typedef struct {+ int *items; /* indices into idx->entries */+ int count;+ int cap;+} lsh_bucket_t;++/* Band hash table: 65536 buckets per band (16-bit hash of r=2 values). */+enum { LSH_BUCKET_COUNT = 65536, LSH_BUCKET_MASK = 65535 };++struct cbm_lsh_index {+ /* b=32 bands, each with LSH_BUCKET_COUNT buckets */+ lsh_bucket_t bands[CBM_LSH_BANDS][LSH_BUCKET_COUNT];+ /* All entries stored for lifetime management */+ cbm_lsh_entry_t *entries;+ int entry_count;+ int entry_cap;+ /* Candidate result buffer (reused across queries) */+ const cbm_lsh_entry_t **result_buf;+ int result_count;+ int result_cap;+};++/* Compute band hash for band `b` from a MinHash signature.+ * Uses r=2 consecutive values starting at position b*r. */+static uint32_t band_hash(const cbm_minhash_t *fp, int band) {+ int base = band * CBM_LSH_ROWS;+ /* Combine r=2 values into a single hash */+ uint32_t combined[CBM_LSH_ROWS];+ for (int r = 0; r < CBM_LSH_ROWS; r++) {+ combined[r] = fp->values[base + r];+ }+ uint64_t h = XXH3_64bits(combined, sizeof(combined));+ return (uint32_t)(h & LSH_BUCKET_MASK);+}++static void bucket_push(lsh_bucket_t *bucket, int entry_index) {+ if (bucket->count >= bucket->cap) {+ int new_cap = bucket->cap < BUCKET_INIT_CAP ? BUCKET_INIT_CAP : bucket->cap * GROW_FACTOR;+ int *new_items = realloc(bucket->items, (size_t)new_cap * sizeof(int));+ if (!new_items) {+ return;+ }+ bucket->items = new_items;+ bucket->cap = new_cap;+ }+ bucket->items[bucket->count++] = entry_index;+}++cbm_lsh_index_t *cbm_lsh_new(void) {+ cbm_lsh_index_t *idx = calloc(SKIP_ONE, sizeof(cbm_lsh_index_t));+ return idx;+}++void cbm_lsh_insert(cbm_lsh_index_t *idx, const cbm_lsh_entry_t *entry) {+ if (!idx || !entry || !entry->fingerprint) {+ return;+ }++ /* Store a copy of the entry */+ if (idx->entry_count >= idx->entry_cap) {+ int new_cap =+ idx->entry_cap < ENTRY_INIT_CAP ? ENTRY_INIT_CAP : idx->entry_cap * GROW_FACTOR;+ cbm_lsh_entry_t *new_entries =+ realloc(idx->entries, (size_t)new_cap * sizeof(cbm_lsh_entry_t));+ if (!new_entries) {+ return;+ }+ idx->entries = new_entries;+ idx->entry_cap = new_cap;+ }+ int entry_idx = idx->entry_count;+ idx->entries[entry_idx] = *entry;+ idx->entry_count++;++ /* Insert index into each band's bucket */+ for (int b = 0; b < CBM_LSH_BANDS; b++) {+ uint32_t h = band_hash(entry->fingerprint, b);+ bucket_push(&idx->bands[b][h], entry_idx);+ }+}++/* Check if a node_id is already in the result buffer. */+static bool result_contains(const cbm_lsh_index_t *idx, int64_t node_id) {+ for (int j = 0; j < idx->result_count; j++) {+ if (idx->result_buf[j]->node_id == node_id) {+ return true;+ }+ }+ return false;+}++/* Append a candidate to the result buffer, growing if needed. Returns false on OOM. */+static bool result_push(cbm_lsh_index_t *idx, const cbm_lsh_entry_t *candidate) {+ if (idx->result_count >= idx->result_cap) {+ int new_cap =+ idx->result_cap < RESULT_INIT_CAP ? RESULT_INIT_CAP : idx->result_cap * GROW_FACTOR;+ const cbm_lsh_entry_t **new_buf =+ realloc(idx->result_buf, (size_t)new_cap * sizeof(const cbm_lsh_entry_t *));+ if (!new_buf) {+ return false;+ }+ idx->result_buf = new_buf;+ idx->result_cap = new_cap;+ }+ idx->result_buf[idx->result_count++] = candidate;+ return true;+}++void cbm_lsh_query(const cbm_lsh_index_t *idx, const cbm_minhash_t *fp,+ const cbm_lsh_entry_t ***out, int *count) {+ *out = NULL;+ *count = 0;++ if (!idx || !fp) {+ return;+ }++ /* Cast away const for result buffer management — query is logically const */+ cbm_lsh_index_t *mut_idx = (cbm_lsh_index_t *)idx;+ mut_idx->result_count = 0;++ for (int b = 0; b < CBM_LSH_BANDS; b++) {+ uint32_t h = band_hash(fp, b);+ const lsh_bucket_t *bucket = &idx->bands[b][h];+ for (int i = 0; i < bucket->count; i++) {+ const cbm_lsh_entry_t *candidate = &idx->entries[bucket->items[i]];+ if (result_contains(idx, candidate->node_id)) {+ continue;+ }+ if (!result_push(mut_idx, candidate)) {+ break;+ }+ }+ }++ *out = mut_idx->result_buf;+ *count = mut_idx->result_count;+}++void cbm_lsh_free(cbm_lsh_index_t *idx) {+ if (!idx) {+ return;+ }+ /* Free bucket arrays */+ for (int b = 0; b < CBM_LSH_BANDS; b++) {+ for (int h = 0; h < LSH_BUCKET_COUNT; h++) {+ free(idx->bands[b][h].items);+ }+ }+ free(idx->entries);+ free(idx->result_buf);+ free(idx);+}diff --git a/src/simhash/minhash.h b/src/simhash/minhash.hnew file mode 100644index 000000000..7250cda37--- /dev/null+++ b/src/simhash/minhash.h@@ -0,0 +1,108 @@+/*+ * minhash.h — MinHash fingerprinting + LSH for near-clone detection.+ *+ * Computes K=64 MinHash signatures from AST node-type trigrams using+ * xxHash with distinct seeds. No external dependencies — xxHash is+ * vendored. Pure functions — thread-safe, no shared state.+ *+ * Workflow:+ * 1. cbm_minhash_compute() — during AST extraction (per function)+ * 2. cbm_minhash_jaccard() — pairwise similarity (K=64 agreement)+ * 3. cbm_lsh_* — locality-sensitive hashing for O(n)+ * candidate generation+ */+#ifndef CBM_MINHASH_H+#define CBM_MINHASH_H++#include <stdint.h>+#include <stdbool.h>++/* Number of hash permutations (seeds). Larger K = more accurate Jaccard+ * estimate, but more memory per function. 64 gives ±0.12 standard+ * error on Jaccard — sufficient for a 0.95 threshold. */+#define CBM_MINHASH_K 64++/* Minimum number of normalized AST body nodes required to compute a+ * fingerprint. Functions shorter than this are skipped to prevent+ * trivial getter/setter fingerprint explosion. */+#define CBM_MINHASH_MIN_NODES 10++/* Default Jaccard threshold for SIMILAR_TO edge emission. */+#define CBM_MINHASH_JACCARD_THRESHOLD 0.95++/* Maximum SIMILAR_TO edges per node (prevents utility function explosion). */+#define CBM_MINHASH_MAX_EDGES_PER_NODE 10++/* LSH parameters: b bands × r rows. Threshold ≈ (1/b)^(1/r). */+#define CBM_LSH_BANDS 32+#define CBM_LSH_ROWS 2++/* ── MinHash fingerprint ─────────────────────────────────────────── */++/* A MinHash signature: K minimum hash values, one per seed. */+typedef struct {+ uint32_t values[CBM_MINHASH_K];+} cbm_minhash_t;++/* Opaque tree-sitter node — forward declared to avoid pulling in+ * tree_sitter/api.h from every consumer. */+typedef struct TSNode TSNode;++/* Compute MinHash fingerprint for a function body's AST.+ *+ * Walks the subtree rooted at `func_body`, normalises leaf node types+ * (identifiers → "I", strings → "S", numbers → "N", type annotations+ * → "T"), builds trigrams, and hashes each trigram with K seeds.+ *+ * Returns true and fills `out` on success.+ * Returns false if the body has fewer than CBM_MINHASH_MIN_NODES+ * normalised tokens (fingerprint not meaningful). */+bool cbm_minhash_compute(TSNode func_body, const char *source, int language, cbm_minhash_t *out);++/* Compute exact Jaccard similarity between two MinHash signatures.+ * Returns value in [0.0, 1.0]. */+double cbm_minhash_jaccard(const cbm_minhash_t *a, const cbm_minhash_t *b);++/* Hex encoding: K uint32 values × 8 hex chars each = 512 chars. */+enum { CBM_MINHASH_HEX_LEN = 512 };++/* Buffer size for hex-encoded fingerprint including NUL. */+enum { CBM_MINHASH_HEX_BUF = 513 };++/* JSON overhead for ,"fp":"..." wrapper (key + quotes + comma + colon). */+enum { CBM_MINHASH_JSON_OVERHEAD = 10 };+void cbm_minhash_to_hex(const cbm_minhash_t *fp, char *buf, int bufsize);++/* Decode a hex string back to a MinHash signature.+ * Returns true on success. */+bool cbm_minhash_from_hex(const char *hex, cbm_minhash_t *out);++/* ── LSH index ───────────────────────────────────────────────────── */++/* Opaque LSH index handle. */+typedef struct cbm_lsh_index cbm_lsh_index_t;++/* Entry stored in the LSH index. */+typedef struct {+ int64_t node_id;+ const cbm_minhash_t *fingerprint;+ const char *file_path; /* for same-file tagging */+ const char *file_ext; /* for same-language filtering */+} cbm_lsh_entry_t;++/* Create a new LSH index. */+cbm_lsh_index_t *cbm_lsh_new(void);++/* Insert an entry into the LSH index. */+void cbm_lsh_insert(cbm_lsh_index_t *idx, const cbm_lsh_entry_t *entry);++/* Query candidates similar to the given fingerprint.+ * Returns candidate entries via `out` (caller does NOT free the array+ * — it is owned by the index). Sets `count`. */+void cbm_lsh_query(const cbm_lsh_index_t *idx, const cbm_minhash_t *fp,+ const cbm_lsh_entry_t ***out, int *count);++/* Free the LSH index and all internal storage. */+void cbm_lsh_free(cbm_lsh_index_t *idx);++#endif /* CBM_MINHASH_H */diff --git a/tests/test_main.c b/tests/test_main.cindex c7bb52a08..1c0621e31 100644--- a/tests/test_main.c+++ b/tests/test_main.c@@ -54,6 +54,7 @@ extern void suite_security(void);extern void suite_yaml(void);extern void suite_integration(void);extern void suite_incremental(void);+extern void suite_simhash(void);int main(void) {printf("\n codebase-memory-mcp C test suite\n");@@ -144,6 +145,9 @@ int main(void) {/* YAML parser */RUN_SUITE(yaml);+ /* SimHash / SIMILAR_TO */+ RUN_SUITE(simhash);+/* Integration (end-to-end) */RUN_SUITE(integration);RUN_SUITE(incremental);diff --git a/tests/test_simhash.c b/tests/test_simhash.cnew file mode 100644index 000000000..671fd6e8d--- /dev/null+++ b/tests/test_simhash.c@@ -0,0 +1,1143 @@+/*+ * test_simhash.c — TDD tests for MinHash fingerprinting + SIMILAR_TO edges.+ *+ * Suite 1: MinHash core (compute, normalise, Jaccard)+ * Suite 2: LSH index (build, query, band bucketing)+ * Suite 3: Edge generation via pass_similarity+ * Suite 4: Full pipeline integration with generated test project+ */+#include "test_framework.h"+#include "test_helpers.h"+#include "simhash/minhash.h"+#include "cbm.h"+#include "graph_buffer/graph_buffer.h"+#include "pipeline/pipeline_internal.h"+#include "pipeline/pipeline.h"+#include "store/store.h"+#include "foundation/compat.h"++#include <stdatomic.h>+#include <string.h>+#include <stdio.h>+#include <math.h>++/* ═══════════════════════════════════════════════════════════════════+ * Helpers+ * ═══════════════════════════════════════════════════════════════════ */++/* Extract a single file and return the result. Caller frees. */+static CBMFileResult *extract_one(const char *src, CBMLanguage lang, const char *proj,+ const char *path) {+ return cbm_extract_file(src, (int)strlen(src), lang, proj, path, 0, NULL, NULL);+}++/* Find a definition by name in an extraction result. */+static const CBMDefinition *find_def(const CBMFileResult *r, const char *name) {+ for (int i = 0; i < r->defs.count; i++) {+ if (strcmp(r->defs.items[i].name, name) == 0) {+ return &r->defs.items[i];+ }+ }+ return NULL;+}++/* Count SIMILAR_TO edges in graph buffer. */+static int count_similar_to_edges(const cbm_gbuf_t *gb) {+ int count = 0;+ /* Iterate all edges via label-based node search + edge queries */+ const cbm_gbuf_node_t **funcs = NULL;+ int func_count = 0;+ cbm_gbuf_find_by_label(gb, "Function", &funcs, &func_count);+ for (int i = 0; i < func_count; i++) {+ const cbm_gbuf_edge_t **edges = NULL;+ int edge_count = 0;+ cbm_gbuf_find_edges_by_source_type(gb, funcs[i]->id, "SIMILAR_TO", &edges, &edge_count);+ count += edge_count;+ }+ const cbm_gbuf_node_t **methods = NULL;+ int method_count = 0;+ cbm_gbuf_find_by_label(gb, "Method", &methods, &method_count);+ for (int i = 0; i < method_count; i++) {+ const cbm_gbuf_edge_t **edges = NULL;+ int edge_count = 0;+ cbm_gbuf_find_edges_by_source_type(gb, methods[i]->id, "SIMILAR_TO", &edges, &edge_count);+ count += edge_count;+ }+ return count;+}++/* ═══════════════════════════════════════════════════════════════════+ * Suite 1: MinHash Core+ * ═══════════════════════════════════════════════════════════════════ */++/* Two identical Go functions must produce identical MinHash signatures. */+TEST(minhash_identical_source_same_fingerprint) {+ const char *src =+ "package main\n"+ "func Validate(u User) error {\n"+ " if u.Name == \"\" {\n"+ " return errors.New(\"name required\")\n"+ " }\n"+ " if u.Age < 0 {\n"+ " return errors.New(\"invalid age\")\n"+ " }\n"+ " if u.Email == \"\" {\n"+ " return errors.New(\"email required\")\n"+ " }\n"+ " return nil\n"+ "}\n";++ CBMFileResult *r1 = extract_one(src, CBM_LANG_GO, "test", "a.go");+ CBMFileResult *r2 = extract_one(src, CBM_LANG_GO, "test", "b.go");+ ASSERT_NOT_NULL(r1);+ ASSERT_NOT_NULL(r2);++ const CBMDefinition *d1 = find_def(r1, "Validate");+ const CBMDefinition *d2 = find_def(r2, "Validate");+ ASSERT_NOT_NULL(d1);+ ASSERT_NOT_NULL(d2);+ ASSERT_NOT_NULL(d1->fingerprint);+ ASSERT_NOT_NULL(d2->fingerprint);+ ASSERT_EQ(d1->fingerprint_k, CBM_MINHASH_K);++ /* Identical source → identical fingerprint */+ ASSERT_MEM_EQ(d1->fingerprint, d2->fingerprint,+ (size_t)CBM_MINHASH_K * sizeof(uint32_t));++ cbm_free_result(r1);+ cbm_free_result(r2);+ PASS();+}++/* Renamed variables should produce the same fingerprint (identifiers normalised). */+TEST(minhash_renamed_vars_same_fingerprint) {+ const char *src_a =+ "package main\n"+ "func ValidateUser(u User) error {\n"+ " if u.Name == \"\" {\n"+ " return errors.New(\"name required\")\n"+ " }\n"+ " if u.Age < 0 {\n"+ " return errors.New(\"invalid age\")\n"+ " }\n"+ " if u.Email == \"\" {\n"+ " return errors.New(\"email required\")\n"+ " }\n"+ " return nil\n"+ "}\n";++ const char *src_b =+ "package main\n"+ "func ValidateOrder(o Order) error {\n"+ " if o.Title == \"\" {\n"+ " return errors.New(\"title required\")\n"+ " }\n"+ " if o.Amount < 0 {\n"+ " return errors.New(\"invalid amount\")\n"+ " }\n"+ " if o.Status == \"\" {\n"+ " return errors.New(\"status required\")\n"+ " }\n"+ " return nil\n"+ "}\n";++ CBMFileResult *ra = extract_one(src_a, CBM_LANG_GO, "test", "a.go");+ CBMFileResult *rb = extract_one(src_b, CBM_LANG_GO, "test", "b.go");+ ASSERT_NOT_NULL(ra);+ ASSERT_NOT_NULL(rb);++ const CBMDefinition *da = find_def(ra, "ValidateUser");+ const CBMDefinition *db = find_def(rb, "ValidateOrder");+ ASSERT_NOT_NULL(da);+ ASSERT_NOT_NULL(db);+ ASSERT_NOT_NULL(da->fingerprint);+ ASSERT_NOT_NULL(db->fingerprint);++ double j = cbm_minhash_jaccard(+ (const cbm_minhash_t *)da->fingerprint,+ (const cbm_minhash_t *)db->fingerprint);+ /* Renamed vars + same structure → very high Jaccard */+ ASSERT_TRUE(j >= 0.90);++ cbm_free_result(ra);+ cbm_free_result(rb);+ PASS();+}++/* Completely different function bodies → low Jaccard. */+TEST(minhash_different_code_different_fingerprint) {+ const char *src_a =+ "package main\n"+ "func Validate(u User) error {\n"+ " if u.Name == \"\" {\n"+ " return errors.New(\"name required\")\n"+ " }\n"+ " if u.Age < 0 {\n"+ " return errors.New(\"invalid age\")\n"+ " }\n"+ " if u.Email == \"\" {\n"+ " return errors.New(\"email required\")\n"+ " }\n"+ " return nil\n"+ "}\n";++ const char *src_b =+ "package main\n"+ "import \"net/http\"\n"+ "func HandleRequest(w http.ResponseWriter, r *http.Request) {\n"+ " data := make(map[string]interface{})\n"+ " for k, v := range r.URL.Query() {\n"+ " data[k] = v[0]\n"+ " }\n"+ " json.NewEncoder(w).Encode(data)\n"+ "}\n";++ CBMFileResult *ra = extract_one(src_a, CBM_LANG_GO, "test", "a.go");+ CBMFileResult *rb = extract_one(src_b, CBM_LANG_GO, "test", "b.go");+ ASSERT_NOT_NULL(ra);+ ASSERT_NOT_NULL(rb);++ const CBMDefinition *da = find_def(ra, "Validate");+ const CBMDefinition *db = find_def(rb, "HandleRequest");+ ASSERT_NOT_NULL(da);+ ASSERT_NOT_NULL(db);+ ASSERT_NOT_NULL(da->fingerprint);+ ASSERT_NOT_NULL(db->fingerprint);++ double j = cbm_minhash_jaccard(+ (const cbm_minhash_t *)da->fingerprint,+ (const cbm_minhash_t *)db->fingerprint);+ /* Different structure → low Jaccard */+ ASSERT_TRUE(j < 0.5);++ cbm_free_result(ra);+ cbm_free_result(rb);+ PASS();+}++/* Same function with one added statement → high but not perfect Jaccard. */+TEST(minhash_minor_edit_high_jaccard) {+ const char *src_a =+ "package main\n"+ "func Process(x int) int {\n"+ " if x < 0 {\n"+ " return -1\n"+ " }\n"+ " if x > 100 {\n"+ " return 100\n"+ " }\n"+ " result := x * 2\n"+ " return result\n"+ "}\n";++ const char *src_b =+ "package main\n"+ "func Process(x int) int {\n"+ " if x < 0 {\n"+ " return -1\n"+ " }\n"+ " if x > 100 {\n"+ " return 100\n"+ " }\n"+ " result := x * 2\n"+ " result = result + 1\n"+ " return result\n"+ "}\n";++ CBMFileResult *ra = extract_one(src_a, CBM_LANG_GO, "test", "a.go");+ CBMFileResult *rb = extract_one(src_b, CBM_LANG_GO, "test", "b.go");+ ASSERT_NOT_NULL(ra);+ ASSERT_NOT_NULL(rb);++ const CBMDefinition *da = find_def(ra, "Process");+ const CBMDefinition *db = find_def(rb, "Process");+ ASSERT_NOT_NULL(da);+ ASSERT_NOT_NULL(db);+ ASSERT_NOT_NULL(da->fingerprint);+ ASSERT_NOT_NULL(db->fingerprint);++ double j = cbm_minhash_jaccard(+ (const cbm_minhash_t *)da->fingerprint,+ (const cbm_minhash_t *)db->fingerprint);+ /* Minor edit → moderately high Jaccard. Trigram-based MinHash+ * is sensitive to insertions (shifts the trigram window), so a+ * single added statement may drop Jaccard more than expected.+ * The key property: it's still higher than completely different code. */+ ASSERT_TRUE(j > 0.50);+ ASSERT_TRUE(j < 1.0);++ cbm_free_result(ra);+ cbm_free_result(rb);+ PASS();+}++/* Functions with fewer than MIN_NODES AST body nodes → no fingerprint.+ * Note: even a 2-line Go function can have 15+ AST nodes (Go's AST is verbose).+ * Use a truly minimal function to test the threshold. */+TEST(minhash_empty_body_skipped) {+ const char *src =+ "package main\n"+ "func Noop() {}\n";++ CBMFileResult *r = extract_one(src, CBM_LANG_GO, "test", "tiny.go");+ ASSERT_NOT_NULL(r);++ const CBMDefinition *d = find_def(r, "Noop");+ ASSERT_NOT_NULL(d);+ /* Empty body → fingerprint should be NULL */+ ASSERT_NULL(d->fingerprint);++ cbm_free_result(r);+ PASS();+}++/* Type annotations normalised: int vs long → same fingerprint. */+TEST(minhash_type_annotation_normalized) {+ const char *src_a =+ "package main\n"+ "func Compute(x int, y int) int {\n"+ " if x > y {\n"+ " return x - y\n"+ " }\n"+ " if x < 0 {\n"+ " return -x\n"+ " }\n"+ " result := x + y\n"+ " return result\n"+ "}\n";++ const char *src_b =+ "package main\n"+ "func Compute(x int64, y int64) int64 {\n"+ " if x > y {\n"+ " return x - y\n"+ " }\n"+ " if x < 0 {\n"+ " return -x\n"+ " }\n"+ " result := x + y\n"+ " return result\n"+ "}\n";++ CBMFileResult *ra = extract_one(src_a, CBM_LANG_GO, "test", "a.go");+ CBMFileResult *rb = extract_one(src_b, CBM_LANG_GO, "test", "b.go");+ ASSERT_NOT_NULL(ra);+ ASSERT_NOT_NULL(rb);++ const CBMDefinition *da = find_def(ra, "Compute");+ const CBMDefinition *db = find_def(rb, "Compute");+ ASSERT_NOT_NULL(da);+ ASSERT_NOT_NULL(db);+ ASSERT_NOT_NULL(da->fingerprint);+ ASSERT_NOT_NULL(db->fingerprint);++ double j = cbm_minhash_jaccard(+ (const cbm_minhash_t *)da->fingerprint,+ (const cbm_minhash_t *)db->fingerprint);+ /* Type annotations normalised → high Jaccard */+ ASSERT_TRUE(j >= 0.90);++ cbm_free_result(ra);+ cbm_free_result(rb);+ PASS();+}++/* ═══════════════════════════════════════════════════════════════════+ * Suite 2: Jaccard + LSH+ * ═══════════════════════════════════════════════════════════════════ */++TEST(jaccard_identical) {+ cbm_minhash_t fp;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ fp.values[i] = (uint32_t)(i * 17 + 42);+ }+ double j = cbm_minhash_jaccard(&fp, &fp);+ ASSERT_FLOAT_EQ(j, 1.0, 0.001);+ PASS();+}++TEST(jaccard_disjoint) {+ cbm_minhash_t a, b;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ a.values[i] = (uint32_t)(i * 3 + 1);+ b.values[i] = (uint32_t)(i * 3 + 2); /* all different */+ }+ double j = cbm_minhash_jaccard(&a, &b);+ ASSERT_FLOAT_EQ(j, 0.0, 0.001);+ PASS();+}++TEST(jaccard_partial_overlap) {+ cbm_minhash_t a, b;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ a.values[i] = (uint32_t)(i * 5);+ /* First 48 match, last 16 differ */+ b.values[i] = (i < 48) ? a.values[i] : (uint32_t)(i * 5 + 999);+ }+ double j = cbm_minhash_jaccard(&a, &b);+ ASSERT_FLOAT_EQ(j, 48.0 / 64.0, 0.001);+ PASS();+}++TEST(minhash_hex_roundtrip) {+ cbm_minhash_t original;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ original.values[i] = (uint32_t)(0xDEAD0000 + i);+ }+ char hex[CBM_MINHASH_HEX_LEN + 1];+ cbm_minhash_to_hex(&original, hex, sizeof(hex));+ ASSERT_EQ((int)strlen(hex), CBM_MINHASH_HEX_LEN);++ cbm_minhash_t decoded;+ bool ok = cbm_minhash_from_hex(hex, &decoded);+ ASSERT_TRUE(ok);+ ASSERT_MEM_EQ(&original, &decoded, sizeof(cbm_minhash_t));+ PASS();+}++TEST(lsh_same_bucket_similar) {+ /* Two fingerprints with Jaccard ≈ 0.97 (62/64 match) should share a bucket */+ cbm_minhash_t a, b;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ a.values[i] = (uint32_t)(i * 7 + 13);+ b.values[i] = a.values[i]; /* start identical */+ }+ /* Differ in only 2 positions */+ b.values[0] = 0xFFFFFFFF;+ b.values[1] = 0xFFFFFFFE;++ cbm_lsh_index_t *idx = cbm_lsh_new();+ cbm_lsh_entry_t ea = {.node_id = 1, .fingerprint = &a, .file_path = "a.go", .file_ext = ".go"};+ cbm_lsh_insert(idx, &ea);++ const cbm_lsh_entry_t **candidates = NULL;+ int count = 0;+ cbm_lsh_query(idx, &b, &candidates, &count);++ /* Must find the similar fingerprint as a candidate */+ ASSERT_GT(count, 0);+ bool found = false;+ for (int i = 0; i < count; i++) {+ if (candidates[i]->node_id == 1) {+ found = true;+ }+ }+ ASSERT_TRUE(found);++ cbm_lsh_free(idx);+ PASS();+}++TEST(lsh_different_bucket_dissimilar) {+ /* Two fingerprints with Jaccard ≈ 0.0 should rarely share a bucket */+ cbm_minhash_t a, b;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ a.values[i] = (uint32_t)(i * 3 + 1);+ b.values[i] = (uint32_t)(i * 3 + 2);+ }++ cbm_lsh_index_t *idx = cbm_lsh_new();+ cbm_lsh_entry_t ea = {.node_id = 1, .fingerprint = &a, .file_path = "a.go", .file_ext = ".go"};+ cbm_lsh_insert(idx, &ea);++ const cbm_lsh_entry_t **candidates = NULL;+ int count = 0;+ cbm_lsh_query(idx, &b, &candidates, &count);++ /* Should NOT find as candidate (or very unlikely) */+ bool found = false;+ for (int i = 0; i < count; i++) {+ if (candidates[i]->node_id == 1) {+ found = true;+ }+ }+ ASSERT_FALSE(found);++ cbm_lsh_free(idx);+ PASS();+}++TEST(lsh_index_build_and_query) {+ /* Build index with 100 fingerprints, one known clone, verify found. */+ cbm_minhash_t fps[100];+ for (int i = 0; i < 100; i++) {+ for (int j = 0; j < CBM_MINHASH_K; j++) {+ fps[i].values[j] = (uint32_t)(i * 1000 + j * 13 + 7);+ }+ }+ /* Make fps[50] a near-clone of fps[0] (differ in 2 positions) */+ memcpy(&fps[50], &fps[0], sizeof(cbm_minhash_t));+ fps[50].values[0] = 0xAAAAAAAA;+ fps[50].values[1] = 0xBBBBBBBB;++ cbm_lsh_index_t *idx = cbm_lsh_new();+ for (int i = 0; i < 100; i++) {+ cbm_lsh_entry_t e = {+ .node_id = i + 1,+ .fingerprint = &fps[i],+ .file_path = "f.go",+ .file_ext = ".go",+ };+ cbm_lsh_insert(idx, &e);+ }++ /* Query with fps[0] — should find fps[50] as candidate */+ const cbm_lsh_entry_t **candidates = NULL;+ int count = 0;+ cbm_lsh_query(idx, &fps[0], &candidates, &count);++ bool found_clone = false;+ for (int i = 0; i < count; i++) {+ if (candidates[i]->node_id == 51) { /* fps[50] → node_id 51 */+ found_clone = true;+ }+ }+ ASSERT_TRUE(found_clone);++ cbm_lsh_free(idx);+ PASS();+}++/* ═══════════════════════════════════════════════════════════════════+ * Suite 3: Edge Generation (pass_similarity on graph buffer)+ * ═══════════════════════════════════════════════════════════════════ */++/* Helper: build a fingerprint hex string for a properties_json. */+static void make_fp_props(char *buf, int bufsize, const cbm_minhash_t *fp) {+ char hex[CBM_MINHASH_HEX_LEN + 1];+ cbm_minhash_to_hex(fp, hex, sizeof(hex));+ snprintf(buf, bufsize, "{\"fp\":\"%s\"}", hex);+}++TEST(pass_similarity_creates_edges) {+ cbm_minhash_t fp;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ fp.values[i] = (uint32_t)(i * 7 + 13);+ }+ char props[1024];+ make_fp_props(props, sizeof(props), &fp);++ cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp");+ cbm_gbuf_upsert_node(gb, "Function", "foo", "test.a.foo", "a.go", 1, 10, props);+ cbm_gbuf_upsert_node(gb, "Function", "bar", "test.b.bar", "b.go", 1, 10, props);++ atomic_int cancelled = 0;+ cbm_pipeline_ctx_t ctx = {+ .project_name = "test",+ .repo_path = "/tmp",+ .gbuf = gb,+ .registry = NULL,+ .cancelled = &cancelled,+ };++ int rc = cbm_pipeline_pass_similarity(&ctx);+ ASSERT_EQ(rc, 0);++ int sim_count = count_similar_to_edges(gb);+ ASSERT_EQ(sim_count, 1); /* A→B only (not bidirectional) */++ cbm_gbuf_free(gb);+ PASS();+}++TEST(pass_similarity_no_edges_different) {+ cbm_minhash_t fp_a, fp_b;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ fp_a.values[i] = (uint32_t)(i * 3 + 1);+ fp_b.values[i] = (uint32_t)(i * 3 + 2);+ }+ char props_a[1024], props_b[1024];+ make_fp_props(props_a, sizeof(props_a), &fp_a);+ make_fp_props(props_b, sizeof(props_b), &fp_b);++ cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp");+ cbm_gbuf_upsert_node(gb, "Function", "foo", "test.a.foo", "a.go", 1, 10, props_a);+ cbm_gbuf_upsert_node(gb, "Function", "bar", "test.b.bar", "b.go", 1, 10, props_b);++ atomic_int cancelled = 0;+ cbm_pipeline_ctx_t ctx = {+ .project_name = "test",+ .repo_path = "/tmp",+ .gbuf = gb,+ .registry = NULL,+ .cancelled = &cancelled,+ };++ int rc = cbm_pipeline_pass_similarity(&ctx);+ ASSERT_EQ(rc, 0);++ int sim_count = count_similar_to_edges(gb);+ ASSERT_EQ(sim_count, 0);++ cbm_gbuf_free(gb);+ PASS();+}++TEST(pass_similarity_same_file_tagged) {+ cbm_minhash_t fp;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ fp.values[i] = (uint32_t)(i * 7 + 13);+ }+ char props[1024];+ make_fp_props(props, sizeof(props), &fp);++ cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp");+ int64_t id_a = cbm_gbuf_upsert_node(gb, "Function", "foo", "test.a.foo", "same.go", 1, 10, props);+ cbm_gbuf_upsert_node(gb, "Function", "bar", "test.a.bar", "same.go", 11, 20, props);++ atomic_int cancelled = 0;+ cbm_pipeline_ctx_t ctx = {+ .project_name = "test",+ .repo_path = "/tmp",+ .gbuf = gb,+ .registry = NULL,+ .cancelled = &cancelled,+ };++ cbm_pipeline_pass_similarity(&ctx);++ const cbm_gbuf_edge_t **edges = NULL;+ int edge_count = 0;+ cbm_gbuf_find_edges_by_source_type(gb, id_a, "SIMILAR_TO", &edges, &edge_count);+ ASSERT_EQ(edge_count, 1);+ /* Edge should have same_file property */+ ASSERT_NOT_NULL(strstr(edges[0]->properties_json, "\"same_file\":true"));++ cbm_gbuf_free(gb);+ PASS();+}++TEST(pass_similarity_cross_language_skip) {+ cbm_minhash_t fp;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ fp.values[i] = (uint32_t)(i * 7 + 13);+ }+ char props[1024];+ make_fp_props(props, sizeof(props), &fp);++ cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp");+ cbm_gbuf_upsert_node(gb, "Function", "foo", "test.a.foo", "a.go", 1, 10, props);+ cbm_gbuf_upsert_node(gb, "Function", "bar", "test.b.bar", "b.py", 1, 10, props);++ atomic_int cancelled = 0;+ cbm_pipeline_ctx_t ctx = {+ .project_name = "test",+ .repo_path = "/tmp",+ .gbuf = gb,+ .registry = NULL,+ .cancelled = &cancelled,+ };++ cbm_pipeline_pass_similarity(&ctx);++ int sim_count = count_similar_to_edges(gb);+ ASSERT_EQ(sim_count, 0); /* Different languages → no edge */++ cbm_gbuf_free(gb);+ PASS();+}++TEST(pass_similarity_edge_properties) {+ /* 60 of 64 hashes match → Jaccard = 60/64 ≈ 0.9375 — below threshold, no edge.+ * 62 of 64 match → Jaccard ≈ 0.969 — above threshold, edge with props. */+ cbm_minhash_t fp_a, fp_b;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ fp_a.values[i] = (uint32_t)(i * 7 + 13);+ fp_b.values[i] = fp_a.values[i];+ }+ /* Differ in 2 positions → Jaccard = 62/64 ≈ 0.969 */+ fp_b.values[0] = 0xDEADBEEF;+ fp_b.values[1] = 0xCAFEBABE;++ char props_a[1024], props_b[1024];+ make_fp_props(props_a, sizeof(props_a), &fp_a);+ make_fp_props(props_b, sizeof(props_b), &fp_b);++ cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp");+ int64_t id_a = cbm_gbuf_upsert_node(gb, "Function", "foo", "test.a.foo", "a.go", 1, 10, props_a);+ cbm_gbuf_upsert_node(gb, "Function", "bar", "test.b.bar", "b.go", 1, 10, props_b);++ atomic_int cancelled = 0;+ cbm_pipeline_ctx_t ctx = {+ .project_name = "test",+ .repo_path = "/tmp",+ .gbuf = gb,+ .registry = NULL,+ .cancelled = &cancelled,+ };++ cbm_pipeline_pass_similarity(&ctx);++ const cbm_gbuf_edge_t **edges = NULL;+ int edge_count = 0;+ cbm_gbuf_find_edges_by_source_type(gb, id_a, "SIMILAR_TO", &edges, &edge_count);+ ASSERT_EQ(edge_count, 1);+ ASSERT_NOT_NULL(strstr(edges[0]->properties_json, "\"jaccard\""));+ ASSERT_NOT_NULL(strstr(edges[0]->properties_json, "\"same_file\":false"));++ cbm_gbuf_free(gb);+ PASS();+}++TEST(pass_similarity_max_edges_cap) {+ cbm_minhash_t fp;+ for (int i = 0; i < CBM_MINHASH_K; i++) {+ fp.values[i] = (uint32_t)(i * 7 + 13);+ }+ char props[1024];+ make_fp_props(props, sizeof(props), &fp);++ cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp");+ /* Create 20 functions with identical fingerprints */+ for (int i = 0; i < 20; i++) {+ char name[32], qn[64], path[32];+ snprintf(name, sizeof(name), "func_%d", i);+ snprintf(qn, sizeof(qn), "test.f%d.func_%d", i, i);+ snprintf(path, sizeof(path), "f%d.go", i);+ cbm_gbuf_upsert_node(gb, "Function", name, qn, path, 1, 10, props);+ }++ atomic_int cancelled = 0;+ cbm_pipeline_ctx_t ctx = {+ .project_name = "test",+ .repo_path = "/tmp",+ .gbuf = gb,+ .registry = NULL,+ .cancelled = &cancelled,+ };++ cbm_pipeline_pass_similarity(&ctx);++ /* Each function should have at most CBM_MINHASH_MAX_EDGES_PER_NODE edges */+ const cbm_gbuf_node_t **funcs = NULL;+ int func_count = 0;+ cbm_gbuf_find_by_label(gb, "Function", &funcs, &func_count);+ for (int i = 0; i < func_count; i++) {+ const cbm_gbuf_edge_t **edges = NULL;+ int edge_count = 0;+ cbm_gbuf_find_edges_by_source_type(gb, funcs[i]->id, "SIMILAR_TO", &edges, &edge_count);+ ASSERT_LTE(edge_count, CBM_MINHASH_MAX_EDGES_PER_NODE);+ }++ cbm_gbuf_free(gb);+ PASS();+}++TEST(pass_similarity_short_funcs_skipped) {+ /* Nodes without "fp" in properties → no edges */+ cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp");+ cbm_gbuf_upsert_node(gb, "Function", "tiny1", "test.t.tiny1", "t.go", 1, 3, "{}");+ cbm_gbuf_upsert_node(gb, "Function", "tiny2", "test.t.tiny2", "t.go", 4, 6, "{}");++ atomic_int cancelled = 0;+ cbm_pipeline_ctx_t ctx = {+ .project_name = "test",+ .repo_path = "/tmp",+ .gbuf = gb,+ .registry = NULL,+ .cancelled = &cancelled,+ };++ cbm_pipeline_pass_similarity(&ctx);++ int sim_count = count_similar_to_edges(gb);+ ASSERT_EQ(sim_count, 0);++ cbm_gbuf_free(gb);+ PASS();+}++/* ═══════════════════════════════════════════════════════════════════+ * Suite 4: Full Pipeline Integration (generated test project)+ * ═══════════════════════════════════════════════════════════════════ */++static char g_sim_tmpdir[512];++static int setup_sim_test_repo(void) {+ snprintf(g_sim_tmpdir, sizeof(g_sim_tmpdir), "/tmp/cbm_sim_test_XXXXXX");+ if (!cbm_mkdtemp(g_sim_tmpdir)) {+ return -1;+ }++ /* Near-clone: ValidateUser and ValidateOrder have same structure, different names */+ th_write_file(TH_PATH(g_sim_tmpdir, "pkg/validation/user_validator.go"),+ "package validation\n"+ "\n"+ "import \"errors\"\n"+ "\n"+ "type User struct {\n"+ " Name string\n"+ " Age int\n"+ " Email string\n"+ "}\n"+ "\n"+ "func ValidateUser(u User) error {\n"+ " if u.Name == \"\" {\n"+ " return errors.New(\"name required\")\n"+ " }\n"+ " if u.Age < 0 {\n"+ " return errors.New(\"invalid age\")\n"+ " }\n"+ " if u.Email == \"\" {\n"+ " return errors.New(\"email required\")\n"+ " }\n"+ " return nil\n"+ "}\n");++ th_write_file(TH_PATH(g_sim_tmpdir, "pkg/validation/order_validator.go"),+ "package validation\n"+ "\n"+ "import \"errors\"\n"+ "\n"+ "type Order struct {\n"+ " Title string\n"+ " Amount int\n"+ " Status string\n"+ "}\n"+ "\n"+ "func ValidateOrder(o Order) error {\n"+ " if o.Title == \"\" {\n"+ " return errors.New(\"title required\")\n"+ " }\n"+ " if o.Amount < 0 {\n"+ " return errors.New(\"invalid amount\")\n"+ " }\n"+ " if o.Status == \"\" {\n"+ " return errors.New(\"status required\")\n"+ " }\n"+ " return nil\n"+ "}\n");++ /* Completely different function */+ th_write_file(TH_PATH(g_sim_tmpdir, "pkg/handler/user_handler.go"),+ "package handler\n"+ "\n"+ "import (\n"+ " \"encoding/json\"\n"+ " \"net/http\"\n"+ ")\n"+ "\n"+ "func HandleUser(w http.ResponseWriter, r *http.Request) {\n"+ " data := make(map[string]interface{})\n"+ " for k, v := range r.URL.Query() {\n"+ " data[k] = v[0]\n"+ " }\n"+ " w.Header().Set(\"Content-Type\", \"application/json\")\n"+ " json.NewEncoder(w).Encode(data)\n"+ "}\n");++ /* Tiny function — should be skipped */+ th_write_file(TH_PATH(g_sim_tmpdir, "pkg/util/tiny_helper.go"),+ "package util\n"+ "\n"+ "func Max(a, b int) int {\n"+ " if a > b { return a }\n"+ " return b\n"+ "}\n");++ return 0;+}++static void teardown_sim_test_repo(void) {+ if (g_sim_tmpdir[0]) {+ th_rmtree(g_sim_tmpdir);+ g_sim_tmpdir[0] = '\0';+ }+}++TEST(pipeline_minhash_end_to_end) {+ if (setup_sim_test_repo() != 0) {+ SKIP("failed to create temp dir");+ }++ char db_path[512];+ snprintf(db_path, sizeof(db_path), "%s/test.db", g_sim_tmpdir);++ cbm_pipeline_t *p = cbm_pipeline_new(g_sim_tmpdir, db_path, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p);++ int rc = cbm_pipeline_run(p);+ ASSERT_EQ(rc, 0);++ /* Open store and verify SIMILAR_TO edges */+ cbm_store_t *s = cbm_store_open_path(db_path);+ ASSERT_NOT_NULL(s);++ const char *project = cbm_pipeline_project_name(p);++ /* Find SIMILAR_TO edges */+ cbm_edge_t *edges = NULL;+ int edge_count = 0;+ int find_rc = cbm_store_find_edges_by_type(s, project, "SIMILAR_TO", &edges, &edge_count);+ ASSERT_EQ(find_rc, CBM_STORE_OK);++ /* Should have at least 1 SIMILAR_TO edge (ValidateUser ↔ ValidateOrder) */+ ASSERT_GTE(edge_count, 1);++ /* Verify ValidateUser has a fingerprint property */+ cbm_node_t vu_node = {0};+ char vu_qn[256];+ snprintf(vu_qn, sizeof(vu_qn), "%s.pkg.validation.user_validator.ValidateUser", project);+ int vu_rc = cbm_store_find_node_by_qn(s, project, vu_qn, &vu_node);+ if (vu_rc == CBM_STORE_OK) {+ ASSERT_NOT_NULL(strstr(vu_node.properties_json, "\"fp\""));+ cbm_node_free_fields(&vu_node);+ }++ /* Note: even Max (3 lines) may have a fingerprint — Go's AST is verbose.+ * We only skip truly empty/trivial functions (< 10 AST nodes).+ * The key assertion is that SIMILAR_TO edges exist for the clones. */++ cbm_store_free_edges(edges, edge_count);+ cbm_store_close(s);+ cbm_pipeline_free(p);+ teardown_sim_test_repo();+ PASS();+}++TEST(pipeline_minhash_no_false_positives) {+ snprintf(g_sim_tmpdir, sizeof(g_sim_tmpdir), "/tmp/cbm_sim_nofp_XXXXXX");+ if (!cbm_mkdtemp(g_sim_tmpdir)) {+ SKIP("failed to create temp dir");+ }++ /* 5 diverse functions — no clones */+ th_write_file(TH_PATH(g_sim_tmpdir, "a.go"),+ "package main\n"+ "func SortSlice(s []int) {\n"+ " for i := 0; i < len(s); i++ {\n"+ " for j := i+1; j < len(s); j++ {\n"+ " if s[i] > s[j] {\n"+ " s[i], s[j] = s[j], s[i]\n"+ " }\n"+ " }\n"+ " }\n"+ "}\n");++ th_write_file(TH_PATH(g_sim_tmpdir, "b.go"),+ "package main\n"+ "import \"net/http\"\n"+ "func ServeAPI(mux *http.ServeMux) {\n"+ " mux.HandleFunc(\"/health\", func(w http.ResponseWriter, r *http.Request) {\n"+ " w.WriteHeader(200)\n"+ " w.Write([]byte(\"ok\"))\n"+ " })\n"+ " mux.HandleFunc(\"/ready\", func(w http.ResponseWriter, r *http.Request) {\n"+ " w.WriteHeader(200)\n"+ " w.Write([]byte(\"ready\"))\n"+ " })\n"+ "}\n");++ th_write_file(TH_PATH(g_sim_tmpdir, "c.go"),+ "package main\n"+ "import \"fmt\"\n"+ "func PrintTree(node *Node, depth int) {\n"+ " for i := 0; i < depth; i++ {\n"+ " fmt.Print(\" \")\n"+ " }\n"+ " fmt.Println(node.Value)\n"+ " for _, child := range node.Children {\n"+ " PrintTree(child, depth+1)\n"+ " }\n"+ "}\n");++ char db_path[512];+ snprintf(db_path, sizeof(db_path), "%s/test.db", g_sim_tmpdir);++ cbm_pipeline_t *p = cbm_pipeline_new(g_sim_tmpdir, db_path, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p);++ int rc = cbm_pipeline_run(p);+ ASSERT_EQ(rc, 0);++ cbm_store_t *s = cbm_store_open_path(db_path);+ ASSERT_NOT_NULL(s);++ cbm_edge_t *edges = NULL;+ int edge_count = 0;+ cbm_store_find_edges_by_type(s, cbm_pipeline_project_name(p), "SIMILAR_TO", &edges, &edge_count);++ ASSERT_EQ(edge_count, 0); /* No clones → no SIMILAR_TO edges */++ if (edges) {+ cbm_store_free_edges(edges, edge_count);+ }+ cbm_store_close(s);+ cbm_pipeline_free(p);+ th_rmtree(g_sim_tmpdir);+ g_sim_tmpdir[0] = '\0';+ PASS();+}++TEST(pipeline_minhash_incremental) {+ if (setup_sim_test_repo() != 0) {+ SKIP("failed to create temp dir");+ }++ char db_path[512];+ snprintf(db_path, sizeof(db_path), "%s/test.db", g_sim_tmpdir);++ /* Step 1: Full pipeline → ValidateUser ↔ ValidateOrder edge created */+ cbm_pipeline_t *p1 = cbm_pipeline_new(g_sim_tmpdir, db_path, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p1);+ int rc = cbm_pipeline_run(p1);+ ASSERT_EQ(rc, 0);+ const char *project = cbm_pipeline_project_name(p1);++ /* Verify edge exists */+ cbm_store_t *s1 = cbm_store_open_path(db_path);+ cbm_edge_t *edges1 = NULL;+ int count1 = 0;+ cbm_store_find_edges_by_type(s1, project, "SIMILAR_TO", &edges1, &count1);+ ASSERT_GTE(count1, 1);+ if (edges1) {+ cbm_store_free_edges(edges1, count1);+ }+ cbm_store_close(s1);+ cbm_pipeline_free(p1);++ /* Step 2: Modify order_validator.go to be completely different */+ th_write_file(TH_PATH(g_sim_tmpdir, "pkg/validation/order_validator.go"),+ "package validation\n"+ "\n"+ "import \"net/http\"\n"+ "\n"+ "func HandleOrder(w http.ResponseWriter, r *http.Request) {\n"+ " data := make(map[string]interface{})\n"+ " for k, v := range r.URL.Query() {\n"+ " data[k] = v[0]\n"+ " }\n"+ " w.Header().Set(\"Content-Type\", \"application/json\")\n"+ "}\n");++ /* Step 3: Incremental reindex */+ cbm_pipeline_t *p2 = cbm_pipeline_new(g_sim_tmpdir, db_path, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p2);+ rc = cbm_pipeline_run(p2);+ ASSERT_EQ(rc, 0);++ /* Step 4: Verify old SIMILAR_TO edge is gone */+ cbm_store_t *s2 = cbm_store_open_path(db_path);+ cbm_edge_t *edges2 = NULL;+ int count2 = 0;+ cbm_store_find_edges_by_type(s2, cbm_pipeline_project_name(p2), "SIMILAR_TO", &edges2, &count2);+ ASSERT_EQ(count2, 0); /* Functions no longer similar */+ if (edges2) {+ cbm_store_free_edges(edges2, count2);+ }+ cbm_store_close(s2);+ cbm_pipeline_free(p2);++ teardown_sim_test_repo();+ PASS();+}++TEST(pipeline_minhash_incremental_new_clone) {+ if (setup_sim_test_repo() != 0) {+ SKIP("failed to create temp dir");+ }++ char db_path[512];+ snprintf(db_path, sizeof(db_path), "%s/test.db", g_sim_tmpdir);++ /* Step 1: Full pipeline */+ cbm_pipeline_t *p1 = cbm_pipeline_new(g_sim_tmpdir, db_path, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p1);+ int rc = cbm_pipeline_run(p1);+ ASSERT_EQ(rc, 0);++ cbm_store_t *s1 = cbm_store_open_path(db_path);+ cbm_edge_t *edges1 = NULL;+ int count1 = 0;+ cbm_store_find_edges_by_type(s1, cbm_pipeline_project_name(p1), "SIMILAR_TO", &edges1, &count1);+ int original_count = count1;+ if (edges1) {+ cbm_store_free_edges(edges1, count1);+ }+ cbm_store_close(s1);+ cbm_pipeline_free(p1);++ /* Step 2: Add a new near-clone of ValidateUser */+ th_write_file(TH_PATH(g_sim_tmpdir, "pkg/validation/address_validator.go"),+ "package validation\n"+ "\n"+ "import \"errors\"\n"+ "\n"+ "type Address struct {\n"+ " Street string\n"+ " Zip int\n"+ " City string\n"+ "}\n"+ "\n"+ "func ValidateAddress(a Address) error {\n"+ " if a.Street == \"\" {\n"+ " return errors.New(\"street required\")\n"+ " }\n"+ " if a.Zip < 0 {\n"+ " return errors.New(\"invalid zip\")\n"+ " }\n"+ " if a.City == \"\" {\n"+ " return errors.New(\"city required\")\n"+ " }\n"+ " return nil\n"+ "}\n");++ /* Step 3: Reindex (will be incremental if DB exists, or full) */+ cbm_pipeline_t *p2 = cbm_pipeline_new(g_sim_tmpdir, db_path, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p2);+ rc = cbm_pipeline_run(p2);+ ASSERT_EQ(rc, 0);++ /* Step 4: Should have MORE SIMILAR_TO edges now */+ cbm_store_t *s2 = cbm_store_open_path(db_path);+ cbm_edge_t *edges2 = NULL;+ int count2 = 0;+ cbm_store_find_edges_by_type(s2, cbm_pipeline_project_name(p2), "SIMILAR_TO", &edges2, &count2);+ ASSERT_GT(count2, original_count); /* New clone adds more edges */+ if (edges2) {+ cbm_store_free_edges(edges2, count2);+ }+ cbm_store_close(s2);+ cbm_pipeline_free(p2);++ teardown_sim_test_repo();+ PASS();+}++/* ═══════════════════════════════════════════════════════════════════+ * Suite Registration+ * ═══════════════════════════════════════════════════════════════════ */++SUITE(simhash) {+ /* Suite 1: MinHash Core */+ RUN_TEST(minhash_identical_source_same_fingerprint);+ RUN_TEST(minhash_renamed_vars_same_fingerprint);+ RUN_TEST(minhash_different_code_different_fingerprint);+ RUN_TEST(minhash_minor_edit_high_jaccard);+ RUN_TEST(minhash_empty_body_skipped);+ RUN_TEST(minhash_type_annotation_normalized);++ /* Suite 2: Jaccard + LSH */+ RUN_TEST(jaccard_identical);+ RUN_TEST(jaccard_disjoint);+ RUN_TEST(jaccard_partial_overlap);+ RUN_TEST(minhash_hex_roundtrip);+ RUN_TEST(lsh_same_bucket_similar);+ RUN_TEST(lsh_different_bucket_dissimilar);+ RUN_TEST(lsh_index_build_and_query);++ /* Suite 3: Edge Generation */+ RUN_TEST(pass_similarity_creates_edges);+ RUN_TEST(pass_similarity_no_edges_different);+ RUN_TEST(pass_similarity_same_file_tagged);+ RUN_TEST(pass_similarity_cross_language_skip);+ RUN_TEST(pass_similarity_edge_properties);+ RUN_TEST(pass_similarity_max_edges_cap);+ RUN_TEST(pass_similarity_short_funcs_skipped);++ /* Suite 4: Full Pipeline Integration */+ RUN_TEST(pipeline_minhash_end_to_end);+ RUN_TEST(pipeline_minhash_no_false_positives);+ RUN_TEST(pipeline_minhash_incremental);+ RUN_TEST(pipeline_minhash_incremental_new_clone);+}