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
feat(graph): queryable computation-bottleneck metrics + indexing perf & fixes
Martin Vogel12683b84a96f
diff --git a/Makefile.cbm b/Makefile.cbmindex d821cb765..75201077f 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -195,6 +195,7 @@ PIPELINE_SRCS = \src/pipeline/pass_k8s.c \src/pipeline/pass_similarity.c \src/pipeline/pass_semantic_edges.c \+ src/pipeline/pass_complexity.c \src/pipeline/pass_cross_repo.c \src/pipeline/artifact.c \src/pipeline/pass_pkgmap.cdiff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.cindex 371e757ee..0539c505f 100644--- a/internal/cbm/cbm.c+++ b/internal/cbm/cbm.c@@ -16,6 +16,7 @@#include <stdint.h> // uint32_t, uint64_t, int64_t#include <stdlib.h>#include <string.h>+#include <ctype.h>#include <time.h> // struct timespec, CLOCK_MONOTONIC// Atomic counters for profiling parse vs extraction time (nanoseconds).@@ -28,6 +29,20 @@ static _Atomic uint64_t total_preprocess_ns = 0;static _Atomic uint64_t total_files_preprocessed = 0;static _Atomic uint64_t total_files = 0;+// C/C++ preprocessor #define macros are extracted as Macro nodes (#375). On a+// macro-dense codebase (e.g. the Linux kernel: ~2.4M macros, 49% of all nodes)+// this is the dominant extraction cost, so it is gated to the full/advanced+// index modes. Default ON to preserve behavior for direct callers/tests; the+// pipeline sets it from the index mode before extraction. Set once pre-extract,+// read-only during, so a relaxed atomic is sufficient.+static _Atomic int g_extract_macros = 1;+void cbm_set_macro_extraction(int enabled) {+ atomic_store_explicit(&g_extract_macros, enabled ? 1 : 0, memory_order_relaxed);+}+int cbm_macro_extraction_enabled(void) {+ return atomic_load_explicit(&g_extract_macros, memory_order_relaxed);+}+#define NSEC_PER_SEC 1000000000ULL#define USEC_TO_NSEC 1000ULL/* Use compat.h's cbm_clock_gettime which accepts CLOCK_MONOTONIC (value@@ -251,6 +266,100 @@ void cbm_shutdown(void) {cbm_initialized = 0;}+// --- Bottleneck call-name classification (language-agnostic heuristics) ---++// Case-insensitive equality for short callee names.+static bool name_ieq(const char *a, const char *b) {+ for (; *a && *b; a++, b++) {+ if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) {+ return false;+ }+ }+ return *a == '\0' && *b == '\0';+}++static bool name_in_set(const char *name, const char *const *set) {+ for (const char *const *s = set; *s; s++) {+ if (name_ieq(name, *s)) {+ return true;+ }+ }+ return false;+}++// Linear-scan / membership calls: a hit inside a loop is the textbook hidden+// O(n^2) (cf. Olivo et al., PLDI'15) that syntactic loop-depth alone misses.+static bool is_linear_scan_name(const char *n) {+ static const char *const set[] = {"find", "indexof", "contains", "includes", "search",+ "lookup", "strstr", "strchr", "strrchr", "memchr",+ "find_if", "findindex", "count", "index", NULL};+ return name_in_set(n, set);+}++// Allocation / growable-append calls: repeated inside a loop is the classic+// accidental reallocation / string-concat O(n^2). Names are deliberately+// conservative; meaningless in some languages → simply never matches there.+static bool is_alloc_name(const char *n) {+ static const char *const set[] = {"malloc", "calloc", "realloc", "strdup",+ "strndup", "append", "push_back", "emplace_back",+ "concat", "strcat", "strncat", "push",+ "pushback", NULL};+ return name_in_set(n, set);+}++// Count parameters from a signature string like "(int a, Foo* b, cb (*)(int,int))".+// Fallback for languages where param_names isn't populated (e.g. C keeps only the+// signature text). Counts commas at the top paren level; treats "()"/"(void)" as 0.+// Approximate by design (a structural smell, not an exact arity).+static int count_params_from_signature(const char *sig) {+ if (!sig) {+ return 0;+ }+ const char *p = sig;+ while (*p && *p != '(') {+ p++;+ }+ if (*p != '(') {+ return 0;+ }+ p++;+ const char *list = p;+ int depth = 0;+ int commas = 0;+ bool any = false;+ for (; *p; p++) {+ char ch = *p;+ if (ch == '(' || ch == '[' || ch == '{' || ch == '<') {+ depth++;+ } else if (ch == ')') {+ if (depth == 0) {+ break;+ }+ depth--;+ } else if (ch == ']' || ch == '}' || ch == '>') {+ if (depth > 0) {+ depth--;+ }+ } else if (ch == ',' && depth == 0) {+ commas++;+ } else if (!isspace((unsigned char)ch)) {+ any = true;+ }+ }+ if (!any) {+ return 0; /* "()" */+ }+ if (commas == 0) {+ while (*list == ' ' || *list == '\t') {+ list++;+ }+ if (strncmp(list, "void", 4) == 0 && (list[4] == ')' || list[4] == ' ' || list[4] == '\0')) {+ return 0; /* C "(void)" */+ }+ }+ return commas + 1;+}+// --- Main extraction function ---CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguage language,@@ -396,6 +505,12 @@ CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguage}atomic_fetch_add(&total_lsp_ns, now_ns() - lsp_start);+ // Calls extracted so far all carry ORIGINAL-source line numbers; the C/C+++ // preprocessor second pass below appends calls with EXPANDED-source lines,+ // which must not be used for the def line-range attribution of the bottleneck+ // metrics. Remember the boundary.+ int orig_calls_count = result->calls.count;+// Second pass: preprocess C/C++/CUDA and extract additional macro-hidden calls.// Defs keep original-source line numbers; only CALLS are extracted from expanded source.if (language == CBM_LANG_C || language == CBM_LANG_CPP || language == CBM_LANG_CUDA) {@@ -457,6 +572,97 @@ CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguageatomic_fetch_add(&total_preprocess_ns, now_ns() - pp_start);}+ // Bottleneck call-context metrics. Each call is attributed to the INNERMOST+ // enclosing Function/Method def by source-line range (defs and calls in one+ // CBMFileResult share the same file). Range matching is used instead of+ // enclosing_func_qn string matching because some grammars (notably C, whose+ // function_definition has no "name" field) attribute the call's scope to the+ // module rather than the function — line ranges are unambiguous and+ // language-agnostic. Bounded per file (defs x calls), not a repo-scale scan.+ int def_count = result->defs.count;+ bool *has_self = def_count > 0 ? calloc((size_t)def_count, sizeof(bool)) : NULL;+ bool *has_guarded = def_count > 0 ? calloc((size_t)def_count, sizeof(bool)) : NULL;++ // param_count is a standalone structural smell (independent of calls). Prefer+ // the parsed param_names array; fall back to counting from the signature text+ // for languages (e.g. C) that populate only the signature.+ for (int di = 0; di < def_count; di++) {+ CBMDefinition *d = &result->defs.items[di];+ int pc = 0;+ if (d->param_names) {+ while (d->param_names[pc]) {+ pc++;+ }+ }+ if (pc == 0 && d->signature) {+ pc = count_params_from_signature(d->signature);+ }+ d->param_count = pc;+ }++ for (int ci = 0; ci < orig_calls_count; ci++) {+ const CBMCall *c = &result->calls.items[ci];+ if (!c->callee_name || c->start_line <= 0) {+ continue;+ }+ // Innermost enclosing Function/Method def by line range (smallest span).+ int best = -1;+ int best_span = -1;+ for (int di = 0; di < def_count; di++) {+ const CBMDefinition *d = &result->defs.items[di];+ if (!d->name || !d->label ||+ (strcmp(d->label, "Function") != 0 && strcmp(d->label, "Method") != 0)) {+ continue;+ }+ if ((int)d->start_line <= c->start_line && c->start_line <= (int)d->end_line) {+ int span = (int)d->end_line - (int)d->start_line;+ if (best < 0 || span < best_span) {+ best_span = span;+ best = di;+ }+ }+ }+ if (best < 0) {+ continue;+ }+ CBMDefinition *d = &result->defs.items[best];+ // callee_name may be bare ("recur") or qualified ("pkg.recur", "self.recur")+ const char *dot = strrchr(c->callee_name, '.');+ const char *callee_short = dot ? dot + 1 : c->callee_name;+ bool in_loop = c->loop_depth > 0;++ if (strcmp(callee_short, d->name) == 0) {+ // Direct self-recursion. The call graph omits self-edges (pass_calls+ // skips source==target), so detect it here; seeds "recursive".+ d->is_recursive = true;+ if (has_self) {+ has_self[best] = true;+ }+ if (in_loop) {+ d->recursion_in_loop = true; // recursion compounded by a loop+ }+ if (c->branch_depth > 0 && has_guarded) {+ has_guarded[best] = true; // a self-call guarded by some conditional+ }+ }+ if (in_loop && is_linear_scan_name(callee_short)) {+ d->linear_scan_in_loop++; // hidden O(n^2): linear scan inside a loop+ }+ if (in_loop && is_alloc_name(callee_short)) {+ d->alloc_in_loop++; // repeated allocation/append inside a loop+ }+ }++ // Recursive with no self-call guarded by any conditional → no obvious base+ // case on the recursive path: a stronger "potentially unbounded" signal.+ for (int di = 0; di < def_count; di++) {+ if (has_self && has_self[di] && !(has_guarded && has_guarded[di])) {+ result->defs.items[di].unguarded_recursion = true;+ }+ }+ free(has_self);+ free(has_guarded);+uint64_t t2 = now_ns();result->imports_count = result->imports.count;diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.hindex 94462faf1..62e32e2e6 100644--- a/internal/cbm/cbm.h+++ b/internal/cbm/cbm.h@@ -195,6 +195,16 @@ typedef struct {const char *route_path; // HTTP route path from decorator (e.g., "/api/users") or NULLconst char *route_method; // HTTP method from decorator (e.g., "POST") or NULLint complexity; // cyclomatic complexity+ int cognitive; // cognitive complexity (nesting-weighted)+ int loop_count; // number of loop constructs in the body+ int loop_depth; // max nested-loop depth (bottleneck proxy)+ bool is_recursive; // body contains a direct self-call (seed for "recursive")+ int param_count; // number of parameters (large = complexity smell)+ int max_access_depth; // deepest chained member/subscript access (a.b.c.d)+ int linear_scan_in_loop; // count of linear-scan calls (find/contains/indexOf) inside loops+ int alloc_in_loop; // count of allocation/append calls inside loops+ bool recursion_in_loop; // a self-call occurs inside a loop body+ bool unguarded_recursion; // recursive with no self-call guarded by a conditionalint lines; // body line countuint32_t *fingerprint; // MinHash fingerprint (arena-allocated, K values) or NULLint fingerprint_k; // number of hash values (CBM_MINHASH_K or 0)@@ -223,6 +233,9 @@ typedef struct {const char *second_arg_name; // second argument identifier (handler ref) or NULLCBMCallArg args[CBM_MAX_CALL_ARGS]; // first N arguments with expressionsint arg_count; // number of captured arguments+ int loop_depth; // enclosing loop nesting at the call site+ int branch_depth; // enclosing branch nesting at the call site+ int start_line; // 1-based source line of the call (for def range-match)} CBMCall;typedef struct {@@ -532,6 +545,12 @@ uint64_t cbm_get_preprocess_ns(void);uint64_t cbm_get_files_preprocessed(void);void cbm_reset_profile(void);+// Toggle C/C++ preprocessor Macro-node extraction (#375). The pipeline enables+// it only for full/advanced index modes (it dominates extraction on macro-dense+// codebases). Default ON. Set before extraction; read-only during.+void cbm_set_macro_extraction(int enabled);+int cbm_macro_extraction_enabled(void);+// --- Internal helpers used by extractors ---// Growable array push functions (arena-allocated, no individual free needed).diff --git a/internal/cbm/extract_calls.c b/internal/cbm/extract_calls.cindex 8a7247809..b165975e5 100644--- a/internal/cbm/extract_calls.c+++ b/internal/cbm/extract_calls.c@@ -727,6 +727,9 @@ void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, WalkCBMCall call = {0};call.callee_name = callee;call.enclosing_func_qn = state->enclosing_func_qn;+ call.loop_depth = state->loop_depth; // enclosing loop nesting at this call+ call.branch_depth = state->branch_depth; // enclosing branch nesting at this call+ call.start_line = (int)ts_node_start_point(node).row + TS_LINE_OFFSET;TSNode args = ts_node_child_by_field_name(node, TS_FIELD("arguments"));if (!ts_node_is_null(args)) {diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.cindex 99aae339e..1a813b4f9 100644--- a/internal/cbm/extract_defs.c+++ b/internal/cbm/extract_defs.c@@ -1671,6 +1671,17 @@ static void resolve_cpp_trailing_return(CBMArena *a, TSNode func_node, const cha}}+/* Compute and store the structural complexity metrics for a definition. */+static void set_def_complexity(CBMDefinition *def, TSNode body, const CBMLangSpec *spec) {+ cbm_complexity_t cx;+ cbm_compute_complexity(body, spec->branching_node_types, &cx);+ def->complexity = cx.cyclomatic;+ def->cognitive = cx.cognitive;+ def->loop_count = cx.loop_count;+ def->loop_depth = cx.loop_depth;+ def->max_access_depth = cx.max_access_depth;+}+static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {CBMArena *a = ctx->arena;@@ -1744,7 +1755,7 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec// Complexityif (spec->branching_node_types && spec->branching_node_types[0]) {- def.complexity = cbm_count_branching(node, spec->branching_node_types);+ set_def_complexity(&def, node, spec);}// MinHash fingerprint@@ -2277,7 +2288,7 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, const char *class_def.docstring = extract_docstring(a, child, ctx->source, ctx->language);if (spec->branching_node_types && spec->branching_node_types[0]) {- def.complexity = cbm_count_branching(child, spec->branching_node_types);+ set_def_complexity(&def, child, spec);}// MinHash fingerprint@@ -2425,7 +2436,7 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec}if (spec->branching_node_types && spec->branching_node_types[0]) {- def.complexity = cbm_count_branching(child, spec->branching_node_types);+ set_def_complexity(&def, child, spec);}// MinHash fingerprint@@ -3829,7 +3840,11 @@ static void walk_defs(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec,if (is_c_preprocessor_lang(ctx->language) &&(strcmp(kind, "preproc_def") == 0 || strcmp(kind, "preproc_function_def") == 0)) {- extract_c_macro_def(ctx, node);+ // Gated to full/advanced index modes — macros dominate extraction on+ // macro-dense codebases (e.g. the Linux kernel). See #375.+ if (cbm_macro_extraction_enabled()) {+ extract_c_macro_def(ctx, node);+ }continue; // the macro body is a preproc_arg — nothing more to extract}diff --git a/internal/cbm/extract_unified.c b/internal/cbm/extract_unified.cindex 9100a08bb..c1cb7c2ed 100644--- a/internal/cbm/extract_unified.c+++ b/internal/cbm/extract_unified.c@@ -36,6 +36,8 @@ static void recompute_state(WalkState *state, const char *module_qn) {state->enclosing_class_qn = NULL;state->inside_call = false;state->inside_import = false;+ state->loop_depth = 0;+ state->branch_depth = 0;for (int i = 0; i < state->scope_top; i++) {switch (state->scopes[i].kind) {@@ -51,6 +53,12 @@ static void recompute_state(WalkState *state, const char *module_qn) {case SCOPE_IMPORT:state->inside_import = true;break;+ case SCOPE_LOOP:+ state->loop_depth++;+ break;+ case SCOPE_BRANCH:+ state->branch_depth++;+ break;default:break;}@@ -686,6 +694,15 @@ static void push_boundary_scopes(CBMExtractCtx *ctx, TSNode node, const CBMLangSif (spec->import_node_types && cbm_kind_in_set(node, spec->import_node_types)) {push_scope(state, SCOPE_IMPORT, depth, NULL);}+ /* Loop / branch nesting for bottleneck metrics. Loops are gated on named+ * nodes so anonymous `for`/`while` keyword tokens don't count. A loop is NOT+ * also counted as a branch (many specs list loops in branching_node_types,+ * but a loop is not a base-case guard for the unguarded-recursion signal). */+ if (ts_node_is_named(node) && cbm_is_loop_node_type(ts_node_type(node))) {+ push_scope(state, SCOPE_LOOP, depth, NULL);+ } else if (spec->branching_node_types && cbm_kind_in_set(node, spec->branching_node_types)) {+ push_scope(state, SCOPE_BRANCH, depth, NULL);+ }}void cbm_extract_unified(CBMExtractCtx *ctx) {diff --git a/internal/cbm/extract_unified.h b/internal/cbm/extract_unified.hindex 09d213642..6e2eb60f5 100644--- a/internal/cbm/extract_unified.h+++ b/internal/cbm/extract_unified.h@@ -9,6 +9,8 @@#define SCOPE_CLASS 2#define SCOPE_CALL 3#define SCOPE_IMPORT 4+#define SCOPE_LOOP 5+#define SCOPE_BRANCH 6#define MAX_SCOPES 64@@ -19,6 +21,8 @@ typedef struct {const char *enclosing_class_qn; // current class QN (NULL outside class)bool inside_call; // within a call_node_types subtreebool inside_import; // within an import_node_types subtree+ int loop_depth; // count of enclosing loop scopes (for bottleneck metrics)+ int branch_depth; // count of enclosing branch scopesstruct {const char *qn;diff --git a/internal/cbm/helpers.c b/internal/cbm/helpers.cindex 8dad0813b..d46f46d52 100644--- a/internal/cbm/helpers.c+++ b/internal/cbm/helpers.c@@ -4,6 +4,8 @@#include "lang_specs.h"#include "tree_sitter/api.h" // TSNode, ts_node_*#include "foundation/constants.h"+#include "foundation/compat.h" // CBM_TLS+#include <stdlib.h> // calloc/free for the symbol-set cacheenum {MIN_ROUTE_LEN = 3,@@ -267,12 +269,22 @@ TSNode cbm_find_child_by_kind(TSNode parent, const char *kind) {return null_node;}-bool cbm_kind_in_set(TSNode node, const char **types) {- if (!types) {- return false;- }+/* ── Node-type classification: TSSymbol bitset acceleration ───────────────+ * cbm_kind_in_set is called for nearly every AST node (function/class/call/+ * import/branching sets), so a linear strcmp over the type-name array is a hot+ * path. tree-sitter already assigns each node type a small integer TSSymbol, so+ * we precompute — per (language, type-array) — a bitset of the matching symbol+ * ids and test ts_node_symbol() in O(1) with no string work.+ *+ * The cache is THREAD-LOCAL: extraction workers are independent pthreads, so a+ * per-thread cache needs no locking and is trivially correct. Bitsets are built+ * once per (lang, array) per thread from static spec arrays (bounded, stable).+ * Any type name that fails to resolve to a symbol disables the bitset for that+ * set (exact=false) and we fall back to the exact strcmp behavior — so the+ * result is always identical to the original, only faster. */+static bool kind_in_set_strcmp(TSNode node, const char *const *types) {const char *kind = ts_node_type(node);- for (const char **t = types; *t; t++) {+ for (const char *const *t = types; *t; t++) {if (strcmp(kind, *t) == 0) {return true;}@@ -280,6 +292,92 @@ bool cbm_kind_in_set(TSNode node, const char **types) {return false;}+typedef struct {+ const TSLanguage *lang; /* NULL = empty slot */+ const char *const *types; /* identity key (static spec array pointer) */+ uint64_t *bits; /* symbol bitset; NULL when exact==false */+ uint32_t nsyms; /* ts_language_symbol_count(lang) */+ bool exact; /* false → every name resolved; use strcmp fallback */+} ks_slot_t;++enum { KS_SLOTS = 512, KS_SLOT_MASK = 511, KS_PROBE = 8 };+static CBM_TLS ks_slot_t ks_cache[KS_SLOTS];++static ks_slot_t *ks_build(const TSLanguage *lang, const char *const *types, ks_slot_t *s) {+ s->lang = lang;+ s->types = types;+ s->bits = NULL;+ s->nsyms = 0;+ s->exact = false;+ uint32_t nsyms = ts_language_symbol_count(lang);+ if (nsyms == 0) {+ return s; /* fall back to strcmp */+ }+ uint64_t *bits = calloc(((size_t)nsyms + 63) / 64, sizeof(uint64_t));+ if (!bits) {+ return s;+ }+ bool all_resolved = true;+ for (const char *const *t = types; *t; t++) {+ uint32_t len = (uint32_t)strlen(*t);+ /* A name may be a named node type or an anonymous token ("for", "&&"):+ * set whichever symbol(s) exist so ts_node_symbol matches either. */+ TSSymbol sn = ts_language_symbol_for_name(lang, *t, len, true);+ TSSymbol sa = ts_language_symbol_for_name(lang, *t, len, false);+ bool any = false;+ if (sn != 0 && sn < nsyms) {+ bits[sn >> 6] |= (uint64_t)1 << (sn & 63);+ any = true;+ }+ if (sa != 0 && sa < nsyms) {+ bits[sa >> 6] |= (uint64_t)1 << (sa & 63);+ any = true;+ }+ if (!any) {+ all_resolved = false; /* unknown name → can't represent exactly */+ }+ }+ if (!all_resolved) {+ free(bits);+ return s; /* exact stays false */+ }+ s->bits = bits;+ s->nsyms = nsyms;+ s->exact = true;+ return s;+}++/* Find or build the cache slot for (lang, types). Returns NULL only if the+ * thread-local table is saturated at this hash (extremely rare → strcmp). */+static ks_slot_t *ks_get(const TSLanguage *lang, const char *const *types) {+ uintptr_t h = ((uintptr_t)types >> 4) ^ ((uintptr_t)lang >> 3) ^ ((uintptr_t)types >> 13);+ for (int probe = 0; probe < KS_PROBE; probe++) {+ ks_slot_t *s = &ks_cache[(size_t)(h + (uintptr_t)probe) & KS_SLOT_MASK];+ if (s->lang == NULL) {+ return ks_build(lang, types, s);+ }+ if (s->lang == lang && s->types == types) {+ return s;+ }+ }+ return NULL;+}++bool cbm_kind_in_set(TSNode node, const char **types) {+ if (!types || !types[0]) {+ return false;+ }+ const TSLanguage *lang = ts_node_language(node);+ if (lang) {+ ks_slot_t *s = ks_get(lang, (const char *const *)types);+ if (s && s->exact && s->bits) {+ TSSymbol sym = ts_node_symbol(node);+ return sym < s->nsyms && (((s->bits[sym >> 6] >> (sym & 63)) & 1U) != 0);+ }+ }+ return kind_in_set_strcmp(node, (const char *const *)types);+}+bool cbm_has_ancestor_kind(TSNode node, const char *kind, int max_depth) {TSNode cur = node;for (int i = 0; i < max_depth; i++) {@@ -326,6 +424,126 @@ int cbm_count_branching(TSNode node, const char **branching_types) {return count_branching_iter(node, branching_types);}+// Loop node-type names across tree-sitter grammars, for loop-nesting depth.+bool cbm_is_loop_node_type(const char *kind) {+ static const char *const loops[] = {+ "for_statement", "while_statement", "do_statement",+ "do_while_statement", "for_in_statement", "for_of_statement",+ "for_each_statement", "foreach_statement", "enhanced_for_statement",+ "for_range_loop", "c_style_for_statement", "for_expression",+ "while_expression", "loop_expression", "while_let_expression",+ "repeat_statement", "repeat_while_statement", "until",+ "while_modifier", "until_modifier", "for",+ "while", NULL};+ for (const char *const *l = loops; *l; l++) {+ if (strcmp(kind, *l) == 0) {+ return true;+ }+ }+ return false;+}++// Is `kind` a chained member/subscript access node? Language-agnostic generic+// set covering the common grammars; used only for the structural "access depth"+// smell, so unmatched grammars simply report 0 (never wrong, just silent).+static bool is_member_access_node(const char *kind) {+ static const char *const access[] = {"member_expression",+ "field_expression",+ "selector_expression",+ "field_access",+ "member_access_expression",+ "navigation_expression",+ "attribute",+ "subscript_expression",+ "subscript",+ "index_expression",+ "element_access_expression",+ "scoped_identifier",+ NULL};+ for (const char *const *a = access; *a; a++) {+ if (strcmp(kind, *a) == 0) {+ return true;+ }+ }+ return false;+}++// One traversal computing cyclomatic + cognitive + loop-nesting + access-depth+// metrics. Each frame carries its branch-, loop- and access-nesting depth so+// every metric (cognitive Campbell penalty, loop_depth polynomial-degree proxy,+// max chained access depth) is produced in a single walk.+void cbm_compute_complexity(TSNode node, const char **branching_types, cbm_complexity_t *out) {+ out->cyclomatic = 0;+ out->cognitive = 0;+ out->loop_count = 0;+ out->loop_depth = 0;+ out->max_access_depth = 0;+ if (!branching_types) {+ return;+ }+ struct cx_frame {+ TSNode node;+ int bdepth;+ int ldepth;+ int adepth;+ };+ struct cx_frame stack[BRANCHING_STACK_CAP];+ int top = 0;+ stack[top].node = node;+ stack[top].bdepth = 0;+ stack[top].ldepth = 0;+ stack[top].adepth = 0;+ top++;+ while (top > 0) {+ struct cx_frame f = stack[--top];+ const char *kind = ts_node_type(f.node);+ bool is_branch = false;+ for (const char **t = branching_types; *t; t++) {+ if (strcmp(kind, *t) == 0) {+ is_branch = true;+ break;+ }+ }+ int child_b = f.bdepth;+ int child_l = f.ldepth;+ /* Chained member/subscript access: a.b.c.d nests as access(access(access(a))),+ * so each consecutive access node deepens the chain; non-access nodes reset it. */+ int child_a = 0;+ if (ts_node_is_named(f.node) && is_member_access_node(kind)) {+ child_a = f.adepth + 1;+ if (child_a > out->max_access_depth) {+ out->max_access_depth = child_a;+ }+ }+ if (is_branch) {+ out->cyclomatic++;+ out->cognitive += 1 + f.bdepth; /* +1 plus nesting penalty (Campbell) */+ child_b = f.bdepth + 1;+ }+ /* Only *named* nodes count as loops. In many grammars (Go, C, …) the+ * loop's `for`/`while` keyword is an anonymous child token whose node+ * type literally equals "for"/"while"; without this guard each loop is+ * counted twice and nesting depth is inflated by one. Named loop nodes+ * (e.g. Ruby's `while`/`until`/`for`) still match correctly. */+ if (ts_node_is_named(f.node) && cbm_is_loop_node_type(kind)) {+ out->loop_count++;+ int d = f.ldepth + 1;+ if (d > out->loop_depth) {+ out->loop_depth = d;+ }+ child_l = d;+ }+ uint32_t n = ts_node_child_count(f.node);+ for (int i = (int)n - SKIP_ONE; i >= 0 && top < BRANCHING_STACK_CAP; i--) {+ stack[top].node = ts_node_child(f.node, (uint32_t)i);+ stack[top].bdepth = child_b;+ stack[top].ldepth = child_l;+ stack[top].adepth = child_a;+ top++;+ }+ }+}+// --- Enclosing function detection ---// Language-specific function node types for parent-chain walkdiff --git a/internal/cbm/helpers.h b/internal/cbm/helpers.hindex 73f04b372..3a3217e82 100644--- a/internal/cbm/helpers.h+++ b/internal/cbm/helpers.h@@ -42,6 +42,24 @@ bool cbm_has_ancestor_kind(TSNode node, const char *kind, int max_depth);// Count nodes of given kinds in subtree (for complexity metric).int cbm_count_branching(TSNode node, const char **branching_types);+// Per-function structural complexity, computed in a single AST walk.+typedef struct {+ int cyclomatic; // branching-node count (matches def.complexity)+ int cognitive; // nesting-weighted flow-break count (Campbell-style approximation)+ int loop_count; // total loop constructs in the body+ int loop_depth; // maximum nested-loop depth — structural bottleneck proxy+ int max_access_depth; // deepest chained member/subscript access (a.b.c.d → 4) — structure smell+} cbm_complexity_t;++// Compute the metrics above in one traversal of `node`'s subtree.+// `branching_types` is the language's branching node-type set.+void cbm_compute_complexity(TSNode node, const char **branching_types, cbm_complexity_t *out);++// Is `kind` a loop construct node type? Language-agnostic curated set (for/while/+// do/foreach/repeat/loop variants). Exposed so the unified walk can track loop+// nesting at call sites without re-deriving the set.+bool cbm_is_loop_node_type(const char *kind);+// Is this a module-level node? (not nested inside function/class body)bool cbm_is_module_level(TSNode node, CBMLanguage lang);diff --git a/src/cypher/cypher.c b/src/cypher/cypher.cindex abc1ef7de..af2b319a9 100644--- a/src/cypher/cypher.c+++ b/src/cypher/cypher.c@@ -2060,6 +2060,8 @@ static const char *node_string_field(const cbm_node_t *n, const char *prop) {/* Get node property by name.* store may be NULL; only needed for virtual degree properties. */+static const char *json_extract_prop(const char *json, const char *key, char *buf, size_t buf_sz);+static const char *node_prop(const cbm_node_t *n, const char *prop, cbm_store_t *store) {if (!n || !prop) {return "";@@ -2068,15 +2070,22 @@ static const char *node_prop(const cbm_node_t *n, const char *prop, cbm_store_tif (str) {return str;}- /* Integer properties returned as strings. */- static _Thread_local char int_buf[CBM_SZ_32];+ /* Computed and JSON-derived values live in rotating thread-local buffers:+ * a single row (or an ORDER-BY comparison) reads several of these before any+ * of them is copied out, so returning one shared static buffer would alias+ * every column to the last value read. Mirrors edge_prop's rotation. */+ static _Thread_local char bufs[CYP_BUF_8][CBM_SZ_512];+ static _Thread_local int buf_idx = 0;+ char *out = bufs[buf_idx];+ buf_idx = (buf_idx + SKIP_ONE) % CYP_BUF_8;+if (strcmp(prop, "start_line") == 0) {- snprintf(int_buf, sizeof(int_buf), "%d", n->start_line);- return int_buf;+ snprintf(out, CBM_SZ_512, "%d", n->start_line);+ return out;}if (strcmp(prop, "end_line") == 0) {- snprintf(int_buf, sizeof(int_buf), "%d", n->end_line);- return int_buf;+ snprintf(out, CBM_SZ_512, "%d", n->end_line);+ return out;}/* Virtual computed properties: in_degree/out_degree via CALLS edges.* Enables Cypher dead-code detection: WHERE n.in_degree = '0'. */@@ -2085,8 +2094,18 @@ static const char *node_prop(const cbm_node_t *n, const char *prop, cbm_store_tint out_deg = 0;cbm_store_node_degree(store, n->id, &in_deg, &out_deg);int val = (strcmp(prop, "in_degree") == 0) ? in_deg : out_deg;- snprintf(int_buf, sizeof(int_buf), "%d", val);- return int_buf;+ snprintf(out, CBM_SZ_512, "%d", val);+ return out;+ }+ /* Fall back to any value stored in the node's properties JSON — exposes the+ * extraction metrics (complexity, cognitive, loop_count, loop_depth,+ * transitive_loop_depth, recursive) and any other persisted property to+ * WHERE/RETURN, e.g. WHERE n.loop_depth >= 2. */+ if (n->properties_json && n->properties_json[0] == '{') {+ const char *v = json_extract_prop(n->properties_json, prop, out, CBM_SZ_512);+ if (v && v[0]) {+ return v;+ }}return "";}@@ -3277,7 +3296,20 @@ static const char *project_item(binding_t *b, cbm_return_item_t *item, char *funif (is_scalar_value_func(item->func)) {return apply_string_func(item->func, raw, func_buf, buf_sz);}- return raw;+ /* Copy into the caller's per-column buffer. `raw` may point to node_prop's+ * rotating scratch buffer, which the next column's projection would overwrite+ * before rb_add_row copies the assembled row — aliasing every such column to+ * the last value read. The per-column func_buf gives each column stable storage. */+ if (raw && raw != func_buf && raw[0]) {+ size_t len = strlen(raw);+ if (len >= buf_sz) {+ len = buf_sz - SKIP_ONE;+ }+ memcpy(func_buf, raw, len);+ func_buf[len] = '\0';+ return func_buf;+ }+ return raw ? raw : "";}/* Check if a function name is an aggregate */@@ -3866,15 +3898,21 @@ static void ret_agg_free(ret_agg_entry_t *aggs, int agg_count, int item_count) {/* Execute RETURN with aggregation *//* Build group key and projected values for one binding */static void ret_agg_build_key(cbm_return_clause_t *ret, binding_t *b, char *key, size_t key_sz,- const char **vals) {+ const char **vals, char valbufs[][CBM_SZ_512]) {int klen = 0;for (int ci = 0; ci < ret->count; ci++) {if (ret->items[ci].func) {vals[ci] = "0";continue;}- char func_buf[CBM_SZ_512];- vals[ci] = project_item(b, &ret->items[ci], func_buf, sizeof(func_buf));+ /* project_item may return its own scratch (stable static or a per-column+ * buffer it copied into); persist the value in the caller-owned valbufs+ * so vals[] survives until ret_agg_init_group strdup's it. */+ const char *v = project_item(b, &ret->items[ci], valbufs[ci], CBM_SZ_512);+ if (v != valbufs[ci]) {+ snprintf(valbufs[ci], CBM_SZ_512, "%s", v ? v : "");+ }+ vals[ci] = valbufs[ci];klen += snprintf(key + klen, key_sz - (size_t)klen, "%s|", vals[ci]);if (klen >= (int)key_sz) {klen = (int)key_sz - SKIP_ONE;@@ -3914,7 +3952,8 @@ static void execute_return_agg(cbm_return_clause_t *ret, binding_t *bindings, infor (int bi = 0; bi < bind_count; bi++) {char key[CBM_SZ_1K] = "";const char *vals[CBM_SZ_32];- ret_agg_build_key(ret, &bindings[bi], key, sizeof(key), vals);+ char valbufs[CBM_SZ_32][CBM_SZ_512];+ ret_agg_build_key(ret, &bindings[bi], key, sizeof(key), vals, valbufs);int found = CYP_FOUND_NONE;for (int a = 0; a < agg_count; a++) {diff --git a/src/foundation/platform.c b/src/foundation/platform.cindex 6b51fcfe1..5b533c042 100644--- a/src/foundation/platform.c+++ b/src/foundation/platform.c@@ -11,6 +11,22 @@#include <stdio.h>#include <string.h>+/* Canonicalize a Windows drive letter to upper-case in place: "c:/x" -> "C:/x".+ * Windows drive letters are case-insensitive, but a lowercase one (as agent+ * CWDs often report, e.g. Claude Code's "c:\...") otherwise produces a distinct+ * project key ("c-..." vs "C-...") and, on a case-insensitive FS, a colliding+ * cache file that clobbers the good index (#227/#367/#394). Folding to a single+ * canonical form here — at the one path-normalization choke point — keeps the+ * project key, cache file and integrity check consistent regardless of case.+ * Only the strict drive-root form `X:/` or bare `X:` is touched, so ordinary+ * POSIX paths (which never start that way) are unaffected. */+static void cbm_canonicalize_drive(char *path) {+ if (path && path[0] >= 'a' && path[0] <= 'z' && path[1] == ':' &&+ (path[2] == '/' || path[2] == '\0')) {+ path[0] = (char)(path[0] - 'a' + 'A');+ }+}+#ifdef _WIN32/* ── Windows implementation ────────────────────────────────── */@@ -133,6 +149,7 @@ char *cbm_normalize_path_sep(char *path) {*p = '/';}}+ cbm_canonicalize_drive(path);}return path;}@@ -262,6 +279,7 @@ char *cbm_normalize_path_sep(char *path) {*p = '/';}}+ cbm_canonicalize_drive(path);}return path;}diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex ae953358a..93c3a379e 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -332,7 +332,18 @@ static const tool_def_t TOOLS[] = {"Execute a Cypher query against the knowledge graph for complex multi-hop patterns, ""aggregations, and cross-service analysis. The response includes 'total' (returned ""row count). There is a hard 100k row ceiling — for broad queries add LIMIT in the "- "Cypher itself or use search_graph + offset/limit pagination instead.",+ "Cypher itself or use search_graph + offset/limit pagination instead. "+ "COMPLEXITY / BOTTLENECKS: every Function and Method node carries queryable complexity "+ "properties — cyclomatic (complexity), cognitive, loop_count, loop_depth (max nested-loop "+ "depth, a polynomial-degree proxy), plus interprocedural transitive_loop_depth (worst-case "+ "nested-loop degree propagated along CALLS edges) and a recursive flag. Additional "+ "hot-path signals: linear_scan_in_loop (count of find/contains/indexOf-style scans inside a "+ "loop — the hidden O(n^2) that loop_depth misses), alloc_in_loop (allocations/appends inside "+ "a loop), recursion_in_loop (a self-call inside a loop), unguarded_recursion (recursion with "+ "no conditionally-guarded base case), param_count and max_access_depth (structure smells). "+ "Find all hot-path candidates in one query, e.g. MATCH (f:Function) WHERE "+ "f.transitive_loop_depth >= 3 OR f.linear_scan_in_loop >= 1 RETURN f.qualified_name, "+ "f.transitive_loop_depth, f.linear_scan_in_loop ORDER BY f.transitive_loop_depth DESC.","{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\",\"description\":\"Cypher ""query\"},\"project\":{\"type\":\"string\"},\"max_rows\":{\"type\":\"integer\",""\"description\":"@@ -374,7 +385,10 @@ static const tool_def_t TOOLS[] = {{"get_architecture","Get high-level architecture overview — packages, services, dependencies, and project "- "structure at a glance.",+ "structure at a glance. Includes 'clusters': Leiden community detection over the call/import "+ "graph, surfacing the de-facto modules (each with a label, member count, cohesion score, "+ "representative top_nodes, and the packages/edge_types that bind it) — use these to grasp "+ "the real architectural seams, which often cut across the folder layout.","{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"aspects\":{\"type\":""\"array\",\"items\":{\"type\":\"string\"}}},\"required\":[\"project\"]}"},diff --git a/src/pipeline/pass_complexity.c b/src/pipeline/pass_complexity.cnew file mode 100644index 000000000..8d60747fa--- /dev/null+++ b/src/pipeline/pass_complexity.c@@ -0,0 +1,206 @@+/*+ * pass_complexity.c — Interprocedural complexity propagation (Tier B).+ *+ * Tier A (in the extraction walk) stamps each Function/Method node with local+ * structural metrics: complexity (cyclomatic), cognitive, loop_count, loop_depth.+ * This pass propagates loop_depth along CALLS edges to estimate a worst-case+ * *transitive* nested-loop degree: a function with a depth-1 loop that calls an+ * O(n) helper is effectively O(n^2). The estimate assumes calls may occur inside+ * loops (an upper bound) — it is a queryable bottleneck *candidate* signal, not a+ * proof (true big-O is undecidable; cf. SPEED / Loopus). Cycles in the call graph+ * are broken and flagged via a `recursive` property.+ *+ * Writes two extra node properties: transitive_loop_depth, recursive.+ */+#include "foundation/constants.h"+#include "pipeline/pipeline.h"+#include "pipeline/pipeline_internal.h"+#include "graph_buffer/graph_buffer.h"+#include "foundation/log.h"+#include "foundation/platform.h"+#include "foundation/compat.h"+#include "cbm.h"++#include <stdlib.h>+#include <string.h>+#include <stdio.h>+#include <stdbool.h>++enum { CBM_TLD_MAX_DEPTH = 256 }; /* recursion-depth cap (cycle/stack guard) */++/* Int → string for structured logging (thread-safe ring buffer). */+static const char *itoa_cx(int val) {+ enum { RING = 2, MASK = 1 };+ static CBM_TLS char bufs[RING][CBM_SZ_32];+ static CBM_TLS int idx = 0;+ int i = idx;+ idx = (idx + 1) & MASK;+ snprintf(bufs[i], sizeof(bufs[i]), "%d", val);+ return bufs[i];+}++/* Parse an integer "key":N from a flat JSON object. Returns def if absent. */+static int json_get_int(const char *json, const char *key, int dflt) {+ if (!json) {+ return dflt;+ }+ char pat[CBM_SZ_64];+ snprintf(pat, sizeof(pat), "\"%s\":", key);+ const char *p = strstr(json, pat);+ if (!p) {+ return dflt;+ }+ p += strlen(pat);+ while (*p == ' ' || *p == '\t') {+ p++;+ }+ return (int)strtol(p, NULL, CBM_DECIMAL_BASE);+}++/* Parse a boolean "key":true/false from a flat JSON object. */+static bool json_get_bool(const char *json, const char *key) {+ if (!json) {+ return false;+ }+ char pat[CBM_SZ_64];+ snprintf(pat, sizeof(pat), "\"%s\":", key);+ const char *p = strstr(json, pat);+ if (!p) {+ return false;+ }+ p += strlen(pat);+ while (*p == ' ' || *p == '\t') {+ p++;+ }+ return *p == 't';+}++/* Append transitive_loop_depth + recursive to a node's properties JSON object. */+static void append_complexity_props(cbm_gbuf_node_t *node, int tld, bool recursive) {+ const char *old = node->properties_json ? node->properties_json : "{}";+ size_t olen = strlen(old);+ if (olen < 2 || old[olen - 1] != '}') {+ return; /* not a JSON object — leave untouched */+ }+ bool empty = (olen == 2); /* "{}" */+ char *neu = malloc(olen + CBM_SZ_64);+ if (!neu) {+ return;+ }+ memcpy(neu, old, olen - 1); /* copy without trailing '}' */+ int w = snprintf(neu + (olen - 1), CBM_SZ_64, "%s\"transitive_loop_depth\":%d,\"recursive\":%s}",+ empty ? "" : ",", tld, recursive ? "true" : "false");+ if (w < 0) {+ free(neu);+ return;+ }+ free(node->properties_json);+ node->properties_json = neu;+}++/* Memoized DFS: tld(id) = loop_depth(id) + max over CALLS-callees of tld(callee).+ * state: 0=unvisited, 1=in-progress (back-edge → cycle), 2=done. */+static int tld_dfs(const cbm_gbuf_t *gb, int64_t id, const int *loop_depth, int *tld, char *state,+ bool *recursive, int64_t maxid, int depth) {+ if (id < 1 || id > maxid) {+ return 0;+ }+ if (state[id] == 2) {+ return tld[id];+ }+ if (state[id] == 1) {+ recursive[id] = true; /* back edge → call-graph cycle */+ return 0;+ }+ if (depth > CBM_TLD_MAX_DEPTH) {+ return loop_depth[id];+ }+ state[id] = 1;+ int best = 0;+ const cbm_gbuf_edge_t **edges = NULL;+ int ne = 0;+ cbm_gbuf_find_edges_by_source_type(gb, id, "CALLS", &edges, &ne);+ for (int i = 0; i < ne; i++) {+ int64_t c = edges[i]->target_id;+ if (c == id) {+ recursive[id] = true; /* direct self-recursion */+ continue;+ }+ int ct = tld_dfs(gb, c, loop_depth, tld, state, recursive, maxid, depth + 1);+ if (ct > best) {+ best = ct;+ }+ }+ tld[id] = loop_depth[id] + best;+ state[id] = 2;+ return tld[id];+}++/* Seed each Function/Method node's loop_depth and self_recursive flag, and+ * remember the node pointer for write-back. The self_recursive seed (set at+ * extraction) feeds the final recursive flag; tld_dfs additionally ORs in+ * mutual recursion discovered as a call-graph cycle. */+static void seed_loop_depths(const cbm_gbuf_t *gb, const char *label, int *loop_depth,+ bool *recursive, cbm_gbuf_node_t **nptr, int64_t maxid) {+ const cbm_gbuf_node_t **nodes = NULL;+ int count = 0;+ if (cbm_gbuf_find_by_label(gb, label, &nodes, &count) != 0) {+ return;+ }+ for (int i = 0; i < count; i++) {+ const cbm_gbuf_node_t *n = nodes[i];+ if (n->id >= 1 && n->id <= maxid) {+ loop_depth[n->id] = json_get_int(n->properties_json, "loop_depth", 0);+ recursive[n->id] = json_get_bool(n->properties_json, "self_recursive");+ nptr[n->id] = (cbm_gbuf_node_t *)n;+ }+ }+}++void cbm_pipeline_pass_complexity(cbm_pipeline_ctx_t *ctx) {+ cbm_gbuf_t *gb = ctx->gbuf;+ /* Node and edge IDs are drawn from one shared counter, so node IDs are NOT+ * contiguous 1..node_count — they interleave with edge IDs. Size the lookup+ * arrays by the id ceiling (next_id) so every node id is addressable. */+ int64_t maxid = cbm_gbuf_next_id(gb) - 1;+ if (maxid < 1) {+ return;+ }+ size_t sz = (size_t)maxid + 1;+ int *loop_depth = calloc(sz, sizeof(int));+ int *tld = calloc(sz, sizeof(int));+ char *state = calloc(sz, sizeof(char));+ bool *recursive = calloc(sz, sizeof(bool));+ cbm_gbuf_node_t **nptr = calloc(sz, sizeof(cbm_gbuf_node_t *));+ if (!loop_depth || !tld || !state || !recursive || !nptr) {+ free(loop_depth);+ free(tld);+ free(state);+ free(recursive);+ free(nptr);+ return;+ }++ seed_loop_depths(gb, "Function", loop_depth, recursive, nptr, maxid);+ seed_loop_depths(gb, "Method", loop_depth, recursive, nptr, maxid);++ int updated = 0;+ for (int64_t id = 1; id <= maxid; id++) {+ if (!nptr[id]) {+ continue; /* only Function/Method nodes */+ }+ if (state[id] != 2) {+ tld_dfs(gb, id, loop_depth, tld, state, recursive, maxid, 0);+ }+ append_complexity_props(nptr[id], tld[id], recursive[id]);+ updated++;+ }++ cbm_log_info("pass.complexity", "functions", itoa_cx(updated));++ free(loop_depth);+ free(tld);+ free(state);+ free(recursive);+ free(nptr);+}diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.cindex b3248b1fb..5214caa9e 100644--- a/src/pipeline/pass_definitions.c+++ b/src/pipeline/pass_definitions.c@@ -176,11 +176,35 @@ static void append_json_str_array(char *buf, size_t bufsize, size_t *pos, const/* Build properties JSON for a definition node. */static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def) {- int n = snprintf(buf, bufsize,- "{\"complexity\":%d,\"lines\":%d,\"is_exported\":%s,"- "\"is_test\":%s,\"is_entry_point\":%s",+ /* The complexity/loop/recursion metrics are only meaningful for executable+ * units (Function/Method). Emitting them on the millions of Macro/Field/+ * Variable/Class/Enum nodes — where they are always zero — bloats every+ * node's properties (~150 B), inflating RAM, the gbuf merge copy and the+ * dump. Gate the block to functions; other labels keep the lean base. */+ const bool is_fn =+ def->label && (strcmp(def->label, "Function") == 0 || strcmp(def->label, "Method") == 0);+ int n;+ if (is_fn) {+ n = snprintf(buf, bufsize,+ "{\"complexity\":%d,\"cognitive\":%d,\"loop_count\":%d,\"loop_depth\":%d,"+ "\"self_recursive\":%s,\"param_count\":%d,\"max_access_depth\":%d,"+ "\"linear_scan_in_loop\":%d,\"alloc_in_loop\":%d,\"recursion_in_loop\":%s,"+ "\"unguarded_recursion\":%s,"+ "\"lines\":%d,\"is_exported\":%s,\"is_test\":%s,\"is_entry_point\":%s",+ def->complexity, def->cognitive, def->loop_count, def->loop_depth,+ def->is_recursive ? "true" : "false", def->param_count, def->max_access_depth,+ def->linear_scan_in_loop, def->alloc_in_loop,+ def->recursion_in_loop ? "true" : "false",+ def->unguarded_recursion ? "true" : "false", def->lines,+ def->is_exported ? "true" : "false", def->is_test ? "true" : "false",+ def->is_entry_point ? "true" : "false");+ } else {+ n = snprintf(buf, bufsize,+ "{\"complexity\":%d,\"lines\":%d,\"is_exported\":%s,\"is_test\":%s,"+ "\"is_entry_point\":%s",def->complexity, def->lines, def->is_exported ? "true" : "false",def->is_test ? "true" : "false", def->is_entry_point ? "true" : "false");+ }if (n <= 0 || (size_t)n >= bufsize) {buf[0] = '\0';diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.cindex fa1a06a91..391c25832 100644--- a/src/pipeline/pass_lsp_cross.c+++ b/src/pipeline/pass_lsp_cross.c@@ -293,38 +293,46 @@ bool cbm_pxc_has_cross_lsp(CBMLanguage lang) {}}-/* True when (caller_qn, callee_qn) is already present in arr. Mirrors the- * intra-LSP dedup in py_emit_resolved_call / ts_emit_resolved_call so that- * cross-file entries duplicating per-file output get dropped at append. */-static bool pxc_already_resolved(const CBMResolvedCallArray *arr, const char *caller_qn,- const char *callee_qn) {- if (!arr || !caller_qn || !callee_qn)- return false;- for (int i = 0; i < arr->count; i++) {- const CBMResolvedCall *rc = &arr->items[i];- if (rc->caller_qn && rc->callee_qn && strcmp(rc->caller_qn, caller_qn) == 0 &&- strcmp(rc->callee_qn, callee_qn) == 0) {- return true;- }- }- return false;-}-/* Append cross-file results from `src_out` (allocated in a scratch arena* about to be destroyed) into `dst_calls` (lives in cache_entry->arena),* copying every string field into dst_arena. Skips entries whose- * (caller_qn, callee_qn) is already in dst_calls — avoids inflating the- * array with cross-file duplicates of per-file LSP output. */+ * (caller_qn, callee_qn) is already present — avoids inflating the array with+ * cross-file duplicates of per-file LSP output.+ *+ * Dedup uses a hash set keyed on "caller\x1fcallee", giving O(1) membership.+ * The previous linear strcmp scan made each append O(n), so a file that+ * resolved very many cross-calls turned the whole append into O(n^2) and could+ * peg a core for minutes (observed: an index hung in pxc_append_results/strcmp).+ * The key strings live in a scratch arena that is destroyed after the table. */static void pxc_append_results(CBMArena *dst_arena, CBMResolvedCallArray *dst_calls,const CBMResolvedCallArray *src_out) {if (!dst_calls || !src_out)return;++ CBMArena keys;+ cbm_arena_init(&keys);+ CBMHashTable *seen = cbm_ht_create((uint32_t)(dst_calls->count + src_out->count + 1));++ for (int i = 0; i < dst_calls->count; i++) {+ const CBMResolvedCall *rc = &dst_calls->items[i];+ if (rc->caller_qn && rc->callee_qn) {+ char *k = cbm_arena_sprintf(&keys, "%s\x1f%s", rc->caller_qn, rc->callee_qn);+ if (k) {+ cbm_ht_set(seen, k, (void *)1);+ }+ }+ }+for (int j = 0; j < src_out->count; j++) {const CBMResolvedCall *src = &src_out->items[j];if (!src->caller_qn || !src->callee_qn)continue;- if (pxc_already_resolved(dst_calls, src->caller_qn, src->callee_qn))+ char *k = cbm_arena_sprintf(&keys, "%s\x1f%s", src->caller_qn, src->callee_qn);+ if (k && cbm_ht_has(seen, k))continue;+ if (k) {+ cbm_ht_set(seen, k, (void *)1);+ }CBMResolvedCall dst;memset(&dst, 0, sizeof(dst));dst.caller_qn = cbm_arena_strdup(dst_arena, src->caller_qn);@@ -334,6 +342,9 @@ static void pxc_append_results(CBMArena *dst_arena, CBMResolvedCallArray *dst_cadst.reason = src->reason ? cbm_arena_strdup(dst_arena, src->reason) : NULL;cbm_resolvedcall_push(dst_calls, dst_arena, dst);}++ cbm_ht_free(seen);+ cbm_arena_destroy(&keys);}/* Run cross-file LSP for a single file inside a scratch arena that getsdiff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.cindex 6aec915e8..73a998b4b 100644--- a/src/pipeline/pass_parallel.c+++ b/src/pipeline/pass_parallel.c@@ -211,11 +211,35 @@ static void append_json_str_array(char *buf, size_t bufsize, size_t *pos, const}static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def) {- int n = snprintf(buf, bufsize,- "{\"complexity\":%d,\"lines\":%d,\"is_exported\":%s,"- "\"is_test\":%s,\"is_entry_point\":%s",+ /* Complexity/loop/recursion metrics are meaningful only for Function/Method.+ * Gate the block so the millions of Macro/Field/Variable/Class/Enum nodes+ * keep a lean properties blob (lossless — those fields are always zero for+ * non-functions). Cuts RAM, gbuf-merge copy and dump volume. Mirrors+ * pass_definitions.c::build_def_props — keep both in sync. */+ const bool is_fn =+ def->label && (strcmp(def->label, "Function") == 0 || strcmp(def->label, "Method") == 0);+ int n;+ if (is_fn) {+ n = snprintf(buf, bufsize,+ "{\"complexity\":%d,\"cognitive\":%d,\"loop_count\":%d,\"loop_depth\":%d,"+ "\"self_recursive\":%s,\"param_count\":%d,\"max_access_depth\":%d,"+ "\"linear_scan_in_loop\":%d,\"alloc_in_loop\":%d,\"recursion_in_loop\":%s,"+ "\"unguarded_recursion\":%s,"+ "\"lines\":%d,\"is_exported\":%s,\"is_test\":%s,\"is_entry_point\":%s",+ def->complexity, def->cognitive, def->loop_count, def->loop_depth,+ def->is_recursive ? "true" : "false", def->param_count, def->max_access_depth,+ def->linear_scan_in_loop, def->alloc_in_loop,+ def->recursion_in_loop ? "true" : "false",+ def->unguarded_recursion ? "true" : "false", def->lines,+ def->is_exported ? "true" : "false", def->is_test ? "true" : "false",+ def->is_entry_point ? "true" : "false");+ } else {+ n = snprintf(buf, bufsize,+ "{\"complexity\":%d,\"lines\":%d,\"is_exported\":%s,\"is_test\":%s,"+ "\"is_entry_point\":%s",def->complexity, def->lines, def->is_exported ? "true" : "false",def->is_test ? "true" : "false", def->is_entry_point ? "true" : "false");+ }if (n <= 0 || (size_t)n >= bufsize) {buf[0] = '\0';return;diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.cindex 7062eb87c..f9401a868 100644--- a/src/pipeline/pipeline.c+++ b/src/pipeline/pipeline.c@@ -448,6 +448,9 @@ static void predump_sem(cbm_pipeline_ctx_t *ctx) {static void predump_cfg(cbm_pipeline_ctx_t *ctx) {cbm_pipeline_pass_configlink(ctx);}+static void predump_complexity(cbm_pipeline_ctx_t *ctx) {+ cbm_pipeline_pass_complexity(ctx);+}static void run_predump_passes(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx) {static const struct {@@ -457,9 +460,9 @@ static void run_predump_passes(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx) {} passes[] = {{predump_deco, "decorator_tags", false}, {predump_cfg, "configlink", false},{predump_route, "route_match", false}, {predump_sim, "similarity", true},- {predump_sem, "semantic_edges", true},+ {predump_sem, "semantic_edges", true}, {predump_complexity, "complexity", false},};- enum { PREDUMP_PASS_COUNT = 5 };+ enum { PREDUMP_PASS_COUNT = 6 };struct timespec t;for (int i = 0; i < PREDUMP_PASS_COUNT && !check_cancel(p); i++) {/* "moderate_only" passes (similarity/semantic edges) run in FULL,@@ -915,6 +918,11 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {cbm_clock_gettime(CLOCK_MONOTONIC, &t0);cbm_path_alias_collection_t *path_aliases = NULL;+ /* C/C++ #define Macro nodes (#375) dominate extraction on macro-dense repos+ * (≈49% of nodes on the Linux kernel), so gate them to full mode — moderate+ * and fast skip them entirely. Set before any extraction dispatch. */+ cbm_set_macro_extraction(p->mode == CBM_MODE_FULL);+/* Load user-defined extension overrides (fail-open: NULL on error) */CBM_PROF_START(t_userconfig);p->userconfig = cbm_userconfig_load(p->repo_path);diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.hindex d785455dc..07ab55130 100644--- a/src/pipeline/pipeline_internal.h+++ b/src/pipeline/pipeline_internal.h@@ -472,6 +472,12 @@ int cbm_pipeline_pass_similarity(cbm_pipeline_ctx_t *ctx);* Opt-in: only runs when CBM_SEMANTIC_ENABLED=1. */int cbm_pipeline_pass_semantic_edges(cbm_pipeline_ctx_t *ctx);+/* Pre-dump pass: interprocedural complexity propagation (Tier B).+ * Propagates per-function loop_depth along CALLS edges into a transitive+ * worst-case nested-loop estimate (transitive_loop_depth) and flags call-graph+ * cycles (recursive). Runs on the graph buffer before the dump. */+void cbm_pipeline_pass_complexity(cbm_pipeline_ctx_t *ctx);+/* ── Env URL scanner (pass_envscan.c) ────────────────────────────── */typedef struct {diff --git a/src/semantic/semantic.c b/src/semantic/semantic.cindex b170fa3a0..5218d9da5 100644--- a/src/semantic/semantic.c+++ b/src/semantic/semantic.c@@ -874,7 +874,14 @@ typedef struct {static void cooccur_sparse_one_target(cooccur_sparse_ctx_t *cc, int tid, cbm_sem_vec_t *target) {int occ_start = cc->rev->offsets[tid];int occ_end = cc->rev->offsets[tid + SKIP_ONE];- for (int p = occ_start; p < occ_end; p++) {+ /* Frequent-token subsampling: stride over occurrences when a token is very+ * common so the enriched vector's direction is preserved (it's normalized+ * after) while bounding work to ~CBM_SEM_MAX_OCCUR samples. See semantic.h. */+ int occ_step = SKIP_ONE;+ if (occ_end - occ_start > CBM_SEM_MAX_OCCUR) {+ occ_step = (occ_end - occ_start) / CBM_SEM_MAX_OCCUR;+ }+ for (int p = occ_start; p < occ_end; p += occ_step) {int d = cc->rev->flat[p].doc_id;int i = cc->rev->flat[p].pos;int *ids = cc->doc_token_ids[d];@@ -956,7 +963,12 @@ static inline void sem_vec_add_int8_scaled(cbm_sem_vec_t *dst, const int8_t *srcstatic void cooccur_int8_one_target(cooccur_int8_ctx_t *cc, int tid, cbm_sem_vec_t *target) {int occ_start = cc->rev->offsets[tid];int occ_end = cc->rev->offsets[tid + SKIP_ONE];- for (int p = occ_start; p < occ_end; p++) {+ /* Frequent-token subsampling (see cooccur_sparse_one_target / semantic.h). */+ int occ_step = SKIP_ONE;+ if (occ_end - occ_start > CBM_SEM_MAX_OCCUR) {+ occ_step = (occ_end - occ_start) / CBM_SEM_MAX_OCCUR;+ }+ for (int p = occ_start; p < occ_end; p += occ_step) {int d = cc->rev->flat[p].doc_id;int i = cc->rev->flat[p].pos;int *ids = cc->doc_token_ids[d];diff --git a/src/semantic/semantic.h b/src/semantic/semantic.hindex 561221067..9d9771826 100644--- a/src/semantic/semantic.h+++ b/src/semantic/semantic.h@@ -39,6 +39,16 @@ enum { CBM_SEM_SPARSE_NNZE = 8 };/* Co-occurrence window half-width. */enum { CBM_SEM_WINDOW = 5 };+/* Frequent-token subsampling cap for co-occurrence enrichment. Code token+ * frequencies are Zipfian — a handful of tokens (int, static, return, …) occur+ * in 10^4–10^5 functions and dominate the O(occurrences × window × dim) corpus+ * finalize cost. When a token has more than this many occurrences, we stride-+ * sample down to ~this count: the enriched vector is L2-normalized afterward, so+ * an evenly-spaced subsample preserves its *direction* while bounding the work.+ * Rare/high-IDF (discriminative) tokens fall under the cap and are untouched.+ * Mirrors word2vec/GloVe frequent-word subsampling. */+enum { CBM_SEM_MAX_OCCUR = 512 };+/* 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 edgesdiff --git a/tests/test_cypher.c b/tests/test_cypher.cindex 42f8f59a7..610c905e4 100644--- a/tests/test_cypher.c+++ b/tests/test_cypher.c@@ -2461,6 +2461,45 @@ TEST(cypher_issue305_count_star_alias) {PASS();}+/* Regression: projecting several computed/JSON properties in one row must yield+ * DISTINCT values. node_prop previously returned a single shared static buffer,+ * so every such column aliased the last property read — and because the search+ * key is matched in the JSON, `loop_depth` must not be confused with its suffix+ * `transitive_loop_depth`. Exercises the bottleneck metrics end-to-end. */+TEST(cypher_multi_prop_projection_no_alias) {+ cbm_store_t *s = cbm_store_open_memory();+ cbm_store_upsert_project(s, "test", "/tmp/test");+ cbm_node_t n = {.project = "test",+ .label = "Function",+ .name = "Hot",+ .qualified_name = "test.Hot",+ .file_path = "hot.go",+ .start_line = 10,+ .end_line = 42,+ .properties_json = "{\"complexity\":3,\"cognitive\":7,\"loop_count\":2,"+ "\"loop_depth\":1,\"self_recursive\":false,"+ "\"transitive_loop_depth\":5,\"recursive\":true}"};+ cbm_store_upsert_node(s, &n);++ cbm_cypher_result_t r = {0};+ int rc = cbm_cypher_execute(s,+ "MATCH (f:Function) RETURN f.loop_depth, f.transitive_loop_depth, "+ "f.cognitive, f.complexity, f.start_line, f.end_line",+ "test", 0, &r);+ ASSERT_EQ(rc, 0);+ ASSERT_EQ(r.row_count, 1);+ ASSERT_EQ(r.col_count, 6);+ ASSERT_STR_EQ(r.rows[0][0], "1"); /* loop_depth — NOT the suffix transitive_loop_depth */+ ASSERT_STR_EQ(r.rows[0][1], "5"); /* transitive_loop_depth */+ ASSERT_STR_EQ(r.rows[0][2], "7"); /* cognitive */+ ASSERT_STR_EQ(r.rows[0][3], "3"); /* complexity */+ ASSERT_STR_EQ(r.rows[0][4], "10"); /* start_line (computed) */+ ASSERT_STR_EQ(r.rows[0][5], "42"); /* end_line (computed) — distinct from start_line */+ cbm_cypher_result_free(&r);+ cbm_store_close(s);+ PASS();+}+/* ══════════════════════════════════════════════════════════════════ */SUITE(cypher) {@@ -2511,6 +2550,7 @@ SUITE(cypher) {RUN_TEST(cypher_func_tointeger_tofloat);RUN_TEST(cypher_func_size_reverse);RUN_TEST(cypher_func_multiarg);+ RUN_TEST(cypher_multi_prop_projection_no_alias);RUN_TEST(cypher_exists_no_callers);RUN_TEST(cypher_exists_has_outgoing_calls);RUN_TEST(cypher_exec_calls_relationship);diff --git a/tests/test_extraction.c b/tests/test_extraction.cindex bc6b27951..8bc15e974 100644--- a/tests/test_extraction.c+++ b/tests/test_extraction.c@@ -2579,6 +2579,167 @@ TEST(extract_large_ts_has_functions_issue213) {PASS();}+/* ═══════════════════════════════════════════════════════════════════+ * Group: per-function complexity metrics (Tier A — local AST metrics)+ *+ * cbm_compute_complexity stamps each Function/Method with cyclomatic,+ * cognitive, loop_count and loop_depth in the same tree-sitter walk that+ * extracts the definition. loop_depth (max nested-loop depth) is the+ * polynomial-degree proxy used as a queryable bottleneck signal.+ * ═══════════════════════════════════════════════════════════════════ */++/* Return the first definition with the given name, or NULL. */+static const CBMDefinition *find_def(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;+}++TEST(complexity_nested_loops_depth) {+ CBMFileResult *r = extract("package p\n"+ "func deepLoops() {\n"+ " for i := 0; i < 10; i++ {\n"+ " for j := 0; j < 10; j++ {\n"+ " for k := 0; k < 10; k++ {\n"+ " doWork()\n"+ " }\n"+ " }\n"+ " }\n"+ "}\n",+ CBM_LANG_GO, "t", "deep.go");+ ASSERT_NOT_NULL(r);+ ASSERT_FALSE(r->has_error);+ const CBMDefinition *d = find_def(r, "deepLoops");+ ASSERT_NOT_NULL(d);+ ASSERT_EQ(d->loop_depth, 3); /* three nested for-loops */+ ASSERT_EQ(d->loop_count, 3);+ cbm_free_result(r);+ PASS();+}++TEST(complexity_loop_with_branch) {+ CBMFileResult *r = extract("package p\n"+ "func single() {\n"+ " for i := 0; i < 10; i++ {\n"+ " if i > 5 {\n"+ " doWork()\n"+ " }\n"+ " }\n"+ "}\n",+ CBM_LANG_GO, "t", "single.go");+ ASSERT_NOT_NULL(r);+ ASSERT_FALSE(r->has_error);+ const CBMDefinition *d = find_def(r, "single");+ ASSERT_NOT_NULL(d);+ ASSERT_EQ(d->loop_depth, 1);+ ASSERT_EQ(d->loop_count, 1);+ /* the nested `if` contributes a branch, so cyclomatic > 1 and the+ * nesting-weighted cognitive score is non-zero. */+ ASSERT_GT(d->complexity, 1);+ ASSERT_GT(d->cognitive, 0);+ cbm_free_result(r);+ PASS();+}++TEST(complexity_flat_no_loops) {+ CBMFileResult *r = extract("package p\n"+ "func flat() {\n"+ " doWork()\n"+ " doMore()\n"+ "}\n",+ CBM_LANG_GO, "t", "flat.go");+ ASSERT_NOT_NULL(r);+ ASSERT_FALSE(r->has_error);+ const CBMDefinition *d = find_def(r, "flat");+ ASSERT_NOT_NULL(d);+ ASSERT_EQ(d->loop_depth, 0);+ ASSERT_EQ(d->loop_count, 0);+ cbm_free_result(r);+ PASS();+}++/* A linear-scan call (contains) inside a loop → hidden O(n^2) signal. */+TEST(complexity_linear_scan_in_loop) {+ CBMFileResult *r = extract("package p\n"+ "func scanInLoop(xs []int, t int) bool {\n"+ " for i := 0; i < len(xs); i++ {\n"+ " if contains(xs, t) {\n"+ " return true\n"+ " }\n"+ " }\n"+ " return false\n"+ "}\n",+ CBM_LANG_GO, "t", "scan.go");+ ASSERT_NOT_NULL(r);+ ASSERT_FALSE(r->has_error);+ const CBMDefinition *d = find_def(r, "scanInLoop");+ ASSERT_NOT_NULL(d);+ ASSERT_GT(d->linear_scan_in_loop, 0); /* contains() called inside the for-loop */+ cbm_free_result(r);+ PASS();+}++/* Self-call inside a loop, not guarded by any conditional → recursion_in_loop+ * and unguarded_recursion both set. */+TEST(complexity_recursion_in_loop_unguarded) {+ CBMFileResult *r = extract("package p\n"+ "func recurInLoop(n int) {\n"+ " for i := 0; i < n; i++ {\n"+ " recurInLoop(n - 1)\n"+ " }\n"+ "}\n",+ CBM_LANG_GO, "t", "recur.go");+ ASSERT_NOT_NULL(r);+ ASSERT_FALSE(r->has_error);+ const CBMDefinition *d = find_def(r, "recurInLoop");+ ASSERT_NOT_NULL(d);+ ASSERT_TRUE(d->is_recursive);+ ASSERT_TRUE(d->recursion_in_loop);+ ASSERT_TRUE(d->unguarded_recursion); /* no self-call inside a conditional */+ cbm_free_result(r);+ PASS();+}++/* Self-call inside an `if` (a base-case guard) → recursive but NOT unguarded. */+TEST(complexity_guarded_recursion) {+ CBMFileResult *r = extract("package p\n"+ "func guarded(n int) int {\n"+ " if n > 0 {\n"+ " return guarded(n - 1)\n"+ " }\n"+ " return 0\n"+ "}\n",+ CBM_LANG_GO, "t", "guarded.go");+ ASSERT_NOT_NULL(r);+ ASSERT_FALSE(r->has_error);+ const CBMDefinition *d = find_def(r, "guarded");+ ASSERT_NOT_NULL(d);+ ASSERT_TRUE(d->is_recursive);+ ASSERT_FALSE(d->recursion_in_loop);+ ASSERT_FALSE(d->unguarded_recursion); /* self-call is guarded by `if n > 0` */+ cbm_free_result(r);+ PASS();+}++/* Deep chained member access + parameter count structure smells. */+TEST(complexity_access_depth_and_params) {+ CBMFileResult *r = extract("package p\n"+ "func deepAccess(x Foo, a int, b int, c int) int {\n"+ " return x.alpha.beta.gamma.delta\n"+ "}\n",+ CBM_LANG_GO, "t", "access.go");+ ASSERT_NOT_NULL(r);+ ASSERT_FALSE(r->has_error);+ const CBMDefinition *d = find_def(r, "deepAccess");+ ASSERT_NOT_NULL(d);+ ASSERT_GT(d->max_access_depth, 2); /* x.alpha.beta.gamma.delta */+ ASSERT_GTE(d->param_count, 3); /* x, a, b, c (grouping may vary) */+ cbm_free_result(r);+ PASS();+}+/* ═══════════════════════════════════════════════════════════════════* Suite* ═══════════════════════════════════════════════════════════════════ */@@ -2799,5 +2960,14 @@ SUITE(extraction) {RUN_TEST(extract_java_method_annotations_issue382);RUN_TEST(extract_large_ts_has_functions_issue213);+ /* Per-function complexity metrics (Tier A) */+ RUN_TEST(complexity_nested_loops_depth);+ RUN_TEST(complexity_loop_with_branch);+ RUN_TEST(complexity_flat_no_loops);+ RUN_TEST(complexity_linear_scan_in_loop);+ RUN_TEST(complexity_recursion_in_loop_unguarded);+ RUN_TEST(complexity_guarded_recursion);+ RUN_TEST(complexity_access_depth_and_params);+cbm_shutdown();}diff --git a/tests/test_pipeline.c b/tests/test_pipeline.cindex 69ff13353..1204137bb 100644--- a/tests/test_pipeline.c+++ b/tests/test_pipeline.c@@ -5,6 +5,7 @@* on a temporary directory with known file layout.*/#include "../src/foundation/compat.h"+#include "foundation/platform.h" // cbm_normalize_path_sep (drive-canonicalization regression)#include "test_framework.h"#include "test_helpers.h"#include "pipeline/pipeline.h"@@ -1956,6 +1957,34 @@ TEST(project_name_from_path) {PASS();}+/* Regression for #394/#227/#367: a Windows drive letter is case-insensitive, so+ * "c:/repo" and "C:/repo" must canonicalize to the SAME project key. Otherwise+ * agent CWDs (which report lowercase "c:\...") produce a distinct key + colliding+ * cache file that clobbers the good index, and the lowercase index self-deletes.+ * Pure string logic, so it reproduces on any platform. */+TEST(project_name_drive_letter_case_insensitive_issue394) {+ char *lower = cbm_project_name_from_path("c:/WEBDEV/Cardio-Cloud");+ char *upper = cbm_project_name_from_path("C:/WEBDEV/Cardio-Cloud");+ ASSERT_NOT_NULL(lower);+ ASSERT_NOT_NULL(upper);+ /* Both must fold to the upper-case-drive key, e.g. "C-WEBDEV-Cardio-Cloud". */+ ASSERT_STR_EQ(lower, upper);+ ASSERT_EQ(lower[0], 'C');+ free(lower);+ free(upper);++ /* And the normalizer itself upper-cases the drive root in place. */+ char buf1[32];+ snprintf(buf1, sizeof(buf1), "%s", "c:/x");+ cbm_normalize_path_sep(buf1);+ ASSERT_STR_EQ(buf1, "C:/x");+ char buf2[32];+ snprintf(buf2, sizeof(buf2), "%s", "d:\\proj\\sub");+ cbm_normalize_path_sep(buf2);+ ASSERT_STR_EQ(buf2, "D:/proj/sub");+ PASS();+}+TEST(project_name_uniqueness) {/* Port of TestProjectNameUniqueness */char *a = cbm_project_name_from_path("/tmp/bench/zig/lib/std");@@ -5393,6 +5422,90 @@ TEST(project_name_trailing_slash) {PASS();}+/* ── Complexity propagation pass tests (Tier B) ────────────────── */++/* Find the first Function/Method node with `name` in a label set. Returns a+ * borrowed pointer into `funcs` or NULL. */+static const cbm_node_t *find_node_named(cbm_node_t *funcs, int count, const char *name) {+ for (int i = 0; i < count; i++) {+ if (strcmp(funcs[i].name, name) == 0)+ return &funcs[i];+ }+ return NULL;+}++/* The complexity pass propagates loop_depth along CALLS edges into+ * transitive_loop_depth and flags call-graph cycles as recursive. Caller and+ * callee live in one file so the calls resolve intra-file (most reliable). */+TEST(pipeline_complexity_transitive_loop_depth) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_cx_XXXXXX");+ if (!cbm_mkdtemp(tmpdir))+ SKIP("tmpdir");++ write_temp_file(tmpdir, "cx.go",+ "package p\n\n"+ "func work() {}\n\n"+ "func inner() {\n"+ "\tfor i := 0; i < 10; i++ {\n"+ "\t\tfor j := 0; j < 10; j++ {\n"+ "\t\t\twork()\n"+ "\t\t}\n"+ "\t}\n"+ "}\n\n"+ "func outer() {\n"+ "\tfor i := 0; i < 10; i++ {\n"+ "\t\tinner()\n"+ "\t}\n"+ "}\n\n"+ "func recur(n int) {\n"+ "\tif n > 0 {\n"+ "\t\trecur(n - 1)\n"+ "\t}\n"+ "}\n");++ char db_path[512];+ snprintf(db_path, sizeof(db_path), "%s/cx.db", tmpdir);++ cbm_pipeline_t *p = cbm_pipeline_new(tmpdir, db_path, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p);+ ASSERT_EQ(cbm_pipeline_run(p), 0);++ cbm_store_t *s = cbm_store_open_path(db_path);+ ASSERT_NOT_NULL(s);+ const char *project = cbm_pipeline_project_name(p);++ cbm_node_t *funcs = NULL;+ int func_count = 0;+ ASSERT_EQ(cbm_store_find_nodes_by_label(s, project, "Function", &funcs, &func_count),+ CBM_STORE_OK);+ ASSERT_GT(func_count, 0);++ /* inner: two nested loops, callee work() has depth 0 → tld == 2 */+ const cbm_node_t *inner = find_node_named(funcs, func_count, "inner");+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(inner->properties_json);+ ASSERT_TRUE(strstr(inner->properties_json, "\"transitive_loop_depth\":2") != NULL);++ /* outer: own depth 1 + inner's tld 2 → tld == 3 (interprocedural) */+ const cbm_node_t *outer = find_node_named(funcs, func_count, "outer");+ ASSERT_NOT_NULL(outer);+ ASSERT_NOT_NULL(outer->properties_json);+ ASSERT_TRUE(strstr(outer->properties_json, "\"transitive_loop_depth\":3") != NULL);++ /* recur: self-recursion → recursive:true flagged by the cycle guard */+ const cbm_node_t *recur = find_node_named(funcs, func_count, "recur");+ ASSERT_NOT_NULL(recur);+ ASSERT_NOT_NULL(recur->properties_json);+ ASSERT_TRUE(strstr(recur->properties_json, "\"recursive\":true") != NULL);++ cbm_store_free_nodes(funcs, func_count);+ cbm_store_close(s);+ cbm_pipeline_free(p);+ th_rmtree(tmpdir);+ PASS();+}+SUITE(pipeline) {/* Index lock */RUN_TEST(pipeline_lock_try_acquire);@@ -5418,6 +5531,8 @@ SUITE(pipeline) {RUN_TEST(pipeline_definitions_function_nodes);RUN_TEST(pipeline_definitions_defines_edges);RUN_TEST(pipeline_definitions_properties);+ /* Complexity propagation pass (Tier B) */+ RUN_TEST(pipeline_complexity_transitive_loop_depth);/* Calls pass */RUN_TEST(pipeline_calls_resolution);/* Git history pass */@@ -5457,6 +5572,7 @@ SUITE(pipeline) {RUN_TEST(pipeline_docstring_go_class);/* Project name */RUN_TEST(project_name_from_path);+ RUN_TEST(project_name_drive_letter_case_insensitive_issue394);RUN_TEST(project_name_uniqueness);/* Git diff helpers */RUN_TEST(gitdiff_parse_range_with_count);