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
Cross-service communication discovery + RAM-first incremental indexing
Martin Vogel80680ea36723
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ac0981b3f..958aa6f8c 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -118,8 +118,32 @@ Examples: `fix(store): set busy_timeout before WAL`, `feat(cli): add --progress## Pull Request Guidelines-- **One issue per PR.** Each PR must address exactly one bug, one feature, or one refactor. Do not bundle multiple fixes or feature additions into a single PR. If your change touches multiple areas, split it into separate PRs.-- **Open an issue first.** Every PR should reference a tracking issue (`Fixes #N` or `Closes #N`). This ensures the change is discussed before code is written.+### Before You Write Code++- **Open an issue first — always.** Every PR must reference a tracking issue (`Fixes #N` or `Closes #N`). Describe what you want to change and why. Wait for maintainer feedback before implementing. PRs without a prior issue discussion will be closed.+- **Bug fixes and test additions** are the exception — these are welcome without prior discussion, as long as they're focused.++### What Requires Explicit Maintainer Approval++The following changes will not be merged without prior design discussion in an issue:++- **API surface changes** — adding, removing, renaming, or changing defaults of MCP tools+- **New pipeline passes or indexing algorithms** — anything that changes what gets extracted or how+- **Build system / Makefile changes** — beyond trivial fixes+- **Project configuration** — CLAUDE.md, skill files, .mcp.json, CI workflows+- **New dependencies** — vendored or otherwise+- **Breaking changes** of any kind++If in doubt, open an issue and ask.++### PR Scope and Size++- **One issue per PR.** Each PR must address exactly one bug, one feature, or one refactor. Do not bundle multiple fixes or feature additions into a single PR. Kitchen-sink PRs will be closed with a request to split.+- **Keep PRs small.** A good PR is under 500 lines. If your change is larger, split it into reviewable increments that each stand on their own.+- **Don't mix features with fixes.** If you find a bug while implementing a feature, submit the bug fix as a separate PR.++### Code Requirements+- **C code only** — this project was rewritten from Go to pure C in v0.5.0. Go PRs will be acknowledged and potentially ported, but cannot be merged directly.- Include tests for new functionality- Run `scripts/test.sh` and `scripts/lint.sh` before submittingdiff --git a/Makefile.cbm b/Makefile.cbmindex b3bb4a8c1..be64f665d 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -118,7 +118,8 @@ EXTRACTION_SRCS = \$(CBM_DIR)/extract_env_accesses.c \$(CBM_DIR)/extract_k8s.c \$(CBM_DIR)/helpers.c \- $(CBM_DIR)/lang_specs.c+ $(CBM_DIR)/lang_specs.c \+ $(CBM_DIR)/service_patterns.c# LSP resolvers (compiled as one unit via lsp_all.c)LSP_SRCS = $(CBM_DIR)/lsp_all.c@@ -175,6 +176,7 @@ PIPELINE_SRCS = \src/pipeline/pass_gitdiff.c \src/pipeline/pass_configures.c \src/pipeline/pass_configlink.c \+ src/pipeline/pass_route_nodes.c \src/pipeline/pass_enrichment.c \src/pipeline/pass_envscan.c \src/pipeline/pass_compile_commands.c \diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.cindex 5b70d1858..f8b8aea5e 100644--- a/internal/cbm/cbm.c+++ b/internal/cbm/cbm.c@@ -124,6 +124,11 @@ void cbm_typeassign_push(CBMTypeAssignArray *arr, CBMArena *a, CBMTypeAssign ta)arr->items[arr->count++] = ta;}+void cbm_stringref_push(CBMStringRefArray *arr, CBMArena *a, CBMStringRef sr) {+ GROW_ARRAY(arr, a);+ arr->items[arr->count++] = sr;+}+void cbm_impltrait_push(CBMImplTraitArray *arr, CBMArena *a, CBMImplTrait it) {GROW_ARRAY(arr, a);arr->items[arr->count++] = it;diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.hindex 6b49ae7fc..4ba963aa0 100644--- a/internal/cbm/cbm.h+++ b/internal/cbm/cbm.h@@ -110,6 +110,7 @@ typedef struct {typedef struct {const char *callee_name; // raw callee text ("pkg.Func", "foo")const char *enclosing_func_qn; // QN of enclosing function (or module QN)+ const char *first_string_arg; // first string literal argument (URL, topic, key) or NULL} CBMCall;typedef struct {@@ -149,6 +150,19 @@ typedef struct {const char *enclosing_func_qn; // QN of enclosing function} CBMTypeAssign;+// String reference: URL, config key, or async target found in source.+// Extracted from string literals during AST walk.+typedef enum {+ CBM_STRREF_URL = 0, // REST path or full URL+ CBM_STRREF_CONFIG = 1, // config file path or env var key+} CBMStringRefKind;++typedef struct {+ const char *value; // the string literal content+ const char *enclosing_func_qn; // QN of enclosing function+ CBMStringRefKind kind; // URL, CONFIG+} CBMStringRef;+// Rust: impl Trait for Structtypedef struct {const char *trait_name; // trait name (raw text)@@ -225,6 +239,12 @@ typedef struct {int cap;} CBMTypeAssignArray;+typedef struct {+ CBMStringRef *items;+ int count;+ int cap;+} CBMStringRefArray;+typedef struct {CBMImplTrait *items;int count;@@ -246,6 +266,7 @@ typedef struct {CBMTypeAssignArray type_assigns;CBMImplTraitArray impl_traits; // Rust: impl Trait for Struct pairsCBMResolvedCallArray resolved_calls; // LSP-resolved calls (high confidence)+ CBMStringRefArray string_refs; // URL/config string literals from ASTconst char *module_qn; // module qualified nameconst char **exports; // NULL-terminated (NULL if none)@@ -279,6 +300,14 @@ typedef struct {// --- Extraction context passed to sub-extractors ---+// Module-level string constant map (for constant propagation)+#define CBM_MAX_STRING_CONSTANTS 256+typedef struct {+ const char *names[CBM_MAX_STRING_CONSTANTS];+ const char *values[CBM_MAX_STRING_CONSTANTS];+ int count;+} CBMStringConstantMap;+typedef struct {CBMArena *arena;CBMFileResult *result;@@ -289,8 +318,9 @@ typedef struct {const char *rel_path;const char *module_qn;TSNode root;- EFCache ef_cache; // enclosing function cache- const char *enclosing_class_qn; // for nested class QN computation+ EFCache ef_cache; // enclosing function cache+ const char *enclosing_class_qn; // for nested class QN computation+ CBMStringConstantMap string_constants; // module-level NAME = "value" pairs} CBMExtractCtx;// --- Public API ---@@ -346,6 +376,7 @@ void cbm_rw_push(CBMRWArray *arr, CBMArena *a, CBMReadWrite rw);void cbm_typerefs_push(CBMTypeRefArray *arr, CBMArena *a, CBMTypeRef tr);void cbm_envaccess_push(CBMEnvAccessArray *arr, CBMArena *a, CBMEnvAccess ea);void cbm_typeassign_push(CBMTypeAssignArray *arr, CBMArena *a, CBMTypeAssign ta);+void cbm_stringref_push(CBMStringRefArray *arr, CBMArena *a, CBMStringRef sr);void cbm_impltrait_push(CBMImplTraitArray *arr, CBMArena *a, CBMImplTrait it);void cbm_resolvedcall_push(CBMResolvedCallArray *arr, CBMArena *a, CBMResolvedCall rc);diff --git a/internal/cbm/extract_calls.c b/internal/cbm/extract_calls.cindex 87bfd005c..3eeb20801 100644--- a/internal/cbm/extract_calls.c+++ b/internal/cbm/extract_calls.c@@ -8,6 +8,20 @@#include <string.h>#include <ctype.h>+/* Look up a module-level string constant by name. */+static const char *lookup_string_constant(const CBMExtractCtx *ctx, const char *name) {+ if (!name || !name[0]) {+ return NULL;+ }+ const CBMStringConstantMap *map = &ctx->string_constants;+ for (int i = 0; i < map->count; i++) {+ if (strcmp(map->names[i], name) == 0) {+ return map->values[i];+ }+ }+ return NULL;+}+// Forward declarationsstatic void walk_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec);static char *extract_callee_name(CBMArena *a, TSNode node, const char *source, CBMLanguage lang);@@ -256,6 +270,46 @@ static void walk_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec)CBMCall call;call.callee_name = callee;call.enclosing_func_qn = cbm_enclosing_func_qn_cached(ctx, node);+ call.first_string_arg = NULL;++ /* Extract first string literal argument (URL, topic, key) */+ TSNode args = ts_node_child_by_field_name(node, "arguments", 9);+ if (!ts_node_is_null(args)) {+ uint32_t nc = ts_node_named_child_count(args);+ for (uint32_t ai = 0; ai < nc && ai < 3; ai++) {+ TSNode arg = ts_node_named_child(args, ai);+ const char *ak = ts_node_type(arg);+ if (strcmp(ak, "string") == 0 || strcmp(ak, "string_literal") == 0 ||+ strcmp(ak, "interpreted_string_literal") == 0 ||+ strcmp(ak, "raw_string_literal") == 0 ||+ strcmp(ak, "string_content") == 0) {+ char *text = cbm_node_text(ctx->arena, arg, ctx->source);+ if (text && text[0]) {+ /* Strip quotes */+ int len = (int)strlen(text);+ if (len >= 2 && (text[0] == '"' || text[0] == '\'')) {+ text =+ cbm_arena_strndup(ctx->arena, text + 1, (size_t)(len - 2));+ len -= 2;+ }+ /* Validate: must be printable ASCII, no control chars */+ // NOLINTNEXTLINE(readability-implicit-bool-conversion)+ bool valid = (text != NULL && len > 0 && len < 512);+ for (int vi = 0; vi < len && valid; vi++) {+ unsigned char ch = (unsigned char)text[vi];+ if (ch < 0x20 && ch != '\t') {+ valid = false;+ }+ }+ if (valid) {+ call.first_string_arg = text;+ }+ }+ break;+ }+ }+ }+cbm_calls_push(&ctx->result->calls, ctx->arena, call);}}@@ -294,7 +348,7 @@ static void extract_jsx_refs(CBMExtractCtx *ctx, TSNode node) {return;}- CBMCall call;+ CBMCall call = {0};call.callee_name = name;call.enclosing_func_qn = cbm_enclosing_func_qn_cached(ctx, node);cbm_calls_push(&ctx->result->calls, ctx->arena, call);@@ -321,9 +375,135 @@ void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, Walkif (cbm_kind_in_set(node, spec->call_node_types)) {char *callee = extract_callee_name(ctx->arena, node, ctx->source, ctx->language);if (callee && callee[0] && !cbm_is_keyword(callee, ctx->language)) {- CBMCall call;+ CBMCall call = {0};call.callee_name = callee;call.enclosing_func_qn = state->enclosing_func_qn;++ /* Extract URL/topic/key from call arguments.+ * Strategy: check keyword args first (url=, topic_id=, queue=),+ * then first positional string, then resolve constant references. */+ TSNode args = ts_node_child_by_field_name(node, "arguments", 9);+ if (!ts_node_is_null(args)) {+ /* Keyword patterns that indicate URL/topic/key */+ static const char *url_keywords[] = {"url", "endpoint", "path", "uri",+ "target_url", "base_url", NULL};+ static const char *topic_keywords[] = {"topic", "topic_id", "topic_name",+ "queue", "queue_name", "queue_id",+ "subject", "channel", NULL};++ uint32_t nc = ts_node_named_child_count(args);+ for (uint32_t ai = 0; ai < nc && !call.first_string_arg; ai++) {+ TSNode arg = ts_node_named_child(args, ai);+ const char *ak = ts_node_type(arg);++ /* Check keyword_argument nodes: url="...", topic_id="..." */+ if (strcmp(ak, "keyword_argument") == 0 || strcmp(ak, "pair") == 0) {+ TSNode key_node = ts_node_child_by_field_name(arg, "name", 4);+ TSNode val_node = ts_node_child_by_field_name(arg, "value", 5);+ if (ts_node_is_null(key_node)) {+ key_node = ts_node_child_by_field_name(arg, "key", 3);+ }+ if (ts_node_is_null(key_node) || ts_node_is_null(val_node)) {+ continue;+ }++ char *key = cbm_node_text(ctx->arena, key_node, ctx->source);+ if (!key) {+ continue;+ }++ /* Check if key matches URL or topic patterns */+ bool is_url_kw = false;+ bool is_topic_kw = false;+ for (int ki = 0; url_keywords[ki]; ki++) {+ if (strcmp(key, url_keywords[ki]) == 0) {+ is_url_kw = true;+ break;+ }+ }+ if (!is_url_kw) {+ for (int ki = 0; topic_keywords[ki]; ki++) {+ if (strcmp(key, topic_keywords[ki]) == 0) {+ is_topic_kw = true;+ break;+ }+ }+ }+ if (!is_url_kw && !is_topic_kw) {+ continue;+ }++ /* Extract value — string literal or constant reference */+ const char *vk = ts_node_type(val_node);+ if (strcmp(vk, "string") == 0 || strcmp(vk, "string_literal") == 0 ||+ strcmp(vk, "interpreted_string_literal") == 0 ||+ strcmp(vk, "raw_string_literal") == 0) {+ char *text = cbm_node_text(ctx->arena, val_node, ctx->source);+ if (text && text[0]) {+ int len = (int)strlen(text);+ if (len >= 2 && (text[0] == '"' || text[0] == '\'')) {+ text =+ cbm_arena_strndup(ctx->arena, text + 1, (size_t)(len - 2));+ }+ if (text && text[0]) {+ call.first_string_arg = text;+ }+ }+ } else if (strcmp(vk, "identifier") == 0) {+ /* Constant reference: url=MY_URL_CONSTANT */+ char *const_name = cbm_node_text(ctx->arena, val_node, ctx->source);+ if (const_name) {+ const char *resolved = lookup_string_constant(ctx, const_name);+ if (resolved) {+ call.first_string_arg = resolved;+ }+ }+ }+ continue;+ }++ /* First positional string argument (fallback) */+ if (ai < 3) {+ if (strcmp(ak, "string") == 0 || strcmp(ak, "string_literal") == 0 ||+ strcmp(ak, "interpreted_string_literal") == 0 ||+ strcmp(ak, "raw_string_literal") == 0) {+ char *text = cbm_node_text(ctx->arena, arg, ctx->source);+ if (text && text[0]) {+ int len = (int)strlen(text);+ if (len >= 2 && (text[0] == '"' || text[0] == '\'')) {+ text =+ cbm_arena_strndup(ctx->arena, text + 1, (size_t)(len - 2));+ len -= 2;+ }+ /* Validate printable */+ // NOLINTNEXTLINE(readability-implicit-bool-conversion)+ bool valid = (text != NULL && len > 0 && len < 512);+ for (int vi = 0; vi < len && valid; vi++) {+ if ((unsigned char)text[vi] < 0x20 && text[vi] != '\t') {+ valid = false;+ }+ }+ if (valid) {+ call.first_string_arg = text;+ }+ }+ break;+ }+ /* Positional constant reference: create_task(MY_URL) */+ if (strcmp(ak, "identifier") == 0) {+ char *const_name = cbm_node_text(ctx->arena, arg, ctx->source);+ if (const_name) {+ const char *resolved = lookup_string_constant(ctx, const_name);+ if (resolved) {+ call.first_string_arg = resolved;+ break;+ }+ }+ }+ }+ }+ }+cbm_calls_push(&ctx->result->calls, ctx->arena, call);}}@@ -336,7 +516,7 @@ void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, Walkif (!ts_node_is_null(name_node)) {char *name = cbm_node_text(ctx->arena, name_node, ctx->source);if (name && name[0] >= 'A' && name[0] <= 'Z') {- CBMCall call;+ CBMCall call = {0};call.callee_name = name;call.enclosing_func_qn = state->enclosing_func_qn;cbm_calls_push(&ctx->result->calls, ctx->arena, call);diff --git a/internal/cbm/extract_unified.c b/internal/cbm/extract_unified.cindex f4cfb3cde..1224355e7 100644--- a/internal/cbm/extract_unified.c+++ b/internal/cbm/extract_unified.c@@ -119,6 +119,135 @@ static const char *compute_class_qn(CBMExtractCtx *ctx, TSNode node) {return cbm_fqn_compute(ctx->arena, ctx->project, ctx->rel_path, name);}+/* Forward declaration */+static bool is_string_node(const char *kind);++// --- Module-level constant collection ---++static void handle_string_constants(CBMExtractCtx *ctx, TSNode node, const WalkState *state) {+ /* Only collect at module level (not inside functions/classes) */+ if (state->enclosing_func_qn != NULL && state->enclosing_func_qn != ctx->module_qn) {+ return;+ }++ const char *kind = ts_node_type(node);++ /* Python: expression_statement → assignment → identifier = string */+ /* Go: short_var_declaration, const_spec */+ /* JS/TS: variable_declarator, lexical_declaration */+ if (strcmp(kind, "assignment") != 0 && strcmp(kind, "expression_statement") != 0 &&+ strcmp(kind, "short_var_declaration") != 0 && strcmp(kind, "const_spec") != 0 &&+ strcmp(kind, "variable_declarator") != 0) {+ return;+ }++ /* Find name (left side) and value (right side) */+ TSNode name_node = ts_node_child_by_field_name(node, "left", 4);+ TSNode value_node = ts_node_child_by_field_name(node, "right", 5);++ /* Some grammars use "name" + "value" fields */+ if (ts_node_is_null(name_node)) {+ name_node = ts_node_child_by_field_name(node, "name", 4);+ }+ if (ts_node_is_null(value_node)) {+ value_node = ts_node_child_by_field_name(node, "value", 5);+ }++ if (ts_node_is_null(name_node) || ts_node_is_null(value_node)) {+ return;+ }++ /* Name must be an identifier */+ const char *name_kind = ts_node_type(name_node);+ if (strcmp(name_kind, "identifier") != 0 && strcmp(name_kind, "constant") != 0) {+ return;+ }++ /* Value must be a string literal */+ if (!is_string_node(ts_node_type(value_node))) {+ return;+ }++ char *name = cbm_node_text(ctx->arena, name_node, ctx->source);+ char *value = cbm_node_text(ctx->arena, value_node, ctx->source);+ if (!name || !name[0] || !value || !value[0]) {+ return;+ }++ /* Strip quotes from value */+ int vlen = (int)strlen(value);+ if (vlen >= 2 && (value[0] == '"' || value[0] == '\'')) {+ value = cbm_arena_strndup(ctx->arena, value + 1, (size_t)(vlen - 2));+ if (!value) {+ return;+ }+ }++ /* Add to constant map */+ CBMStringConstantMap *map = &ctx->string_constants;+ if (map->count < CBM_MAX_STRING_CONSTANTS) {+ map->names[map->count] = name;+ map->values[map->count] = value;+ map->count++;+ }+}++// --- String literal collection ---++static bool is_string_node(const char *kind) {+ /* Common string literal node types across tree-sitter grammars */+ // NOLINTNEXTLINE(readability-implicit-bool-conversion)+ return (strcmp(kind, "string_literal") == 0 || strcmp(kind, "string") == 0 ||+ strcmp(kind, "string_content") == 0 ||+ strcmp(kind, "interpreted_string_literal") == 0 ||+ strcmp(kind, "raw_string_literal") == 0 || strcmp(kind, "string_value") == 0 ||+ /* YAML string types */+ strcmp(kind, "double_quote_scalar") == 0 || strcmp(kind, "single_quote_scalar") == 0);+}++static void handle_string_refs(CBMExtractCtx *ctx, TSNode node, const WalkState *state) {+ const char *kind = ts_node_type(node);+ if (!is_string_node(kind)) {+ return;+ }++ /* Extract string content */+ char *text = cbm_node_text(ctx->arena, node, ctx->source);+ if (!text || !text[0]) {+ return;+ }++ /* Strip quotes if present */+ int len = (int)strlen(text);+ const char *content = text;+ if (len >= 2 && (text[0] == '"' || text[0] == '\'')) {+ content = text + 1;+ len -= 2;+ if (len <= 0) {+ return;+ }+ }++ /* Classify */+ int kind_val = cbm_classify_string(content, len);+ if (kind_val < 0) {+ return;+ }++ /* Build null-terminated content string in arena */+ char *val = cbm_arena_strndup(ctx->arena, content, (size_t)len);+ if (!val) {+ return;+ }++ CBMStringRef ref = {+ .value = val,+ .enclosing_func_qn = state->enclosing_func_qn ? state->enclosing_func_qn : ctx->module_qn,+ .kind = (CBMStringRefKind)kind_val,+ };+ cbm_stringref_push(&ctx->result->string_refs, ctx->arena, ref);+}+// --- Main unified cursor walk ---void cbm_extract_unified(CBMExtractCtx *ctx) {@@ -143,6 +272,7 @@ void cbm_extract_unified(CBMExtractCtx *ctx) {recompute_state(&state, ctx->module_qn);// 3. Dispatch to all handlers+ handle_string_constants(ctx, node, &state);handle_calls(ctx, node, spec, &state);handle_usages(ctx, node, spec, &state);handle_throws(ctx, node, spec, &state);@@ -150,6 +280,7 @@ void cbm_extract_unified(CBMExtractCtx *ctx) {handle_type_refs(ctx, node, spec, &state);handle_env_accesses(ctx, node, spec, &state);handle_type_assigns(ctx, node, spec, &state);+ handle_string_refs(ctx, node, &state);// 4. Push scope markers for boundary nodesif (spec->function_node_types && cbm_kind_in_set(node, spec->function_node_types)) {diff --git a/internal/cbm/helpers.c b/internal/cbm/helpers.cindex 0b4147b5b..c3d9b16da 100644--- a/internal/cbm/helpers.c+++ b/internal/cbm/helpers.c@@ -848,3 +848,111 @@ char *cbm_fqn_folder(CBMArena *a, const char *project, const char *rel_dir) {*out = '\0';return buf;}++/* ── String literal classifier ──────────────────────────────────── */++static bool is_url_like(const char *s, int len) {+ if (len < 3) {+ return false;+ }++ /* Full URL: contains :// */+ if (strstr(s, "://")) {+ return true;+ }++ /* REST path: starts with / + alphanumeric */+ if (s[0] == '/') {+ /* Reject file system paths */+ if (len > 4 && (strncmp(s, "/usr/", 5) == 0 || strncmp(s, "/bin/", 5) == 0 ||+ strncmp(s, "/etc/", 5) == 0 || strncmp(s, "/var/", 5) == 0 ||+ strncmp(s, "/tmp/", 5) == 0 || strncmp(s, "/opt/", 5) == 0 ||+ strncmp(s, "/home/", 6) == 0 || strncmp(s, "/dev/", 5) == 0 ||+ strncmp(s, "/sys/", 5) == 0 || strncmp(s, "/proc/", 6) == 0)) {+ return false;+ }+ /* Reject regex patterns */+ if (len > 1 && s[len - 1] == '/') {+ return false;+ }+ if (s[1] == '^') {+ return false;+ }++ /* Reject single / or // */+ if (len == 1) {+ return false;+ }+ if (len == 2 && s[1] == '/') {+ return false;+ }++ /* Reject relative paths ./ ../ */+ if (s[1] == '.') {+ return false;+ }++ /* Must have at least one path segment with alphanumeric */+ for (int i = 1; i < len && i < 20; i++) {+ char c = s[i];+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {+ return true;+ }+ }+ return false;+ }++ return false;+}++static bool has_config_extension(const char *s, int len) {+ static const char *exts[] = {".toml", ".yaml", ".yml", ".json", ".ini",+ ".env", ".cfg", ".conf", ".properties", NULL};+ for (int i = 0; exts[i]; i++) {+ int elen = (int)strlen(exts[i]);+ if (len > elen && strcmp(s + len - elen, exts[i]) == 0) {+ return true;+ }+ }+ return false;+}++static bool is_env_var_pattern(const char *s, int len) {+ if (len < 3 || len > 64) {+ return false;+ }+ bool has_upper = false;+ bool has_underscore = false;+ for (int i = 0; i < len; i++) {+ char c = s[i];+ if (c >= 'A' && c <= 'Z') {+ has_upper = true;+ } else if (c == '_') {+ has_underscore = true;+ } else if (c >= '0' && c <= '9') {+ /* digits ok */+ } else {+ return false;+ }+ }+ // NOLINTNEXTLINE(readability-implicit-bool-conversion)+ return has_upper && has_underscore;+}++int cbm_classify_string(const char *str, int len) {+ if (!str || len < 2) {+ return -1;+ }++ if (is_url_like(str, len)) {+ return CBM_STRREF_URL;+ }+ if (has_config_extension(str, len)) {+ return CBM_STRREF_CONFIG;+ }+ if (is_env_var_pattern(str, len)) {+ return CBM_STRREF_CONFIG;+ }++ return -1;+}diff --git a/internal/cbm/helpers.h b/internal/cbm/helpers.hindex 7a04595eb..f30ad59e4 100644--- a/internal/cbm/helpers.h+++ b/internal/cbm/helpers.h@@ -9,6 +9,10 @@ char *cbm_node_text(CBMArena *a, TSNode node, const char *source);// Check if a string is a language keyword (should be skipped as callee/usage).bool cbm_is_keyword(const char *name, CBMLanguage lang);+// Classify a string literal as URL, config, or neither.+// Returns CBM_STRREF_URL (0), CBM_STRREF_CONFIG (1), or -1 for neither.+int cbm_classify_string(const char *str, int len);+// Check if a name is exported per language convention.bool cbm_is_exported(const char *name, CBMLanguage lang);diff --git a/internal/cbm/lsp/c_lsp.c b/internal/cbm/lsp/c_lsp.cindex d2c901fed..2513a7d09 100644--- a/internal/cbm/lsp/c_lsp.c+++ b/internal/cbm/lsp/c_lsp.c@@ -1239,7 +1239,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {// Check if it's a type name (for constructor calls / casts)const CBMType* type = c_resolve_name_to_type(ctx, name);- if (type && safe_kind(type) == CBM_TYPE_NAMED) {+ if (type && type->kind == CBM_TYPE_NAMED) {// Could be a constructor call — return as typereturn type;}@@ -1303,11 +1303,11 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {// a template param name) and receiver is a TEMPLATE type, substitute using// receiver's template args.// e.g., pair<int, Foo>.second where second has type V → substitute V=Foo- bool is_tparam = (safe_kind(field_type) == CBM_TYPE_TYPE_PARAM);+ bool is_tparam = (field_type->kind == CBM_TYPE_TYPE_PARAM);// Also check NAMED types that match template param names (extract_defs// may register template fields as NAMED("V") rather than TYPE_PARAM("V"))- if (!is_tparam && safe_kind(field_type) == CBM_TYPE_NAMED &&- safe_kind(base) == CBM_TYPE_TEMPLATE) {+ if (!is_tparam && field_type->kind == CBM_TYPE_NAMED &&+ base->kind == CBM_TYPE_TEMPLATE) {const CBMRegisteredType* trt = cbm_registry_lookup_type(ctx->registry, type_qn);if (!trt && ctx->module_qn) {trt = cbm_registry_lookup_type(ctx->registry,@@ -1328,7 +1328,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {}}}- if (is_tparam && safe_kind(base) == CBM_TYPE_TEMPLATE &&+ if (is_tparam && base->kind == CBM_TYPE_TEMPLATE &&base->data.template_type.template_args) {const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, type_qn);if (!rt && ctx->module_qn) {@@ -1406,7 +1406,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {if (f && f->signature) {// If template args present, substitute into return typeif (qi_has_tmpl_args && !ts_node_is_null(qi_tmpl_args) &&- safe_kind(f->signature) == CBM_TYPE_FUNC &&+ f->signature->kind == CBM_TYPE_FUNC &&f->signature->data.func.return_types &&f->signature->data.func.return_types[0]) {const CBMType* base_ret = f->signature->data.func.return_types[0];@@ -1438,7 +1438,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {// (e.g., smart pointer dereference) can extract inner types.// e.g., make_shared<Widget> returns NAMED("std.shared_ptr") →// TEMPLATE("std.shared_ptr", [Widget])- if (safe_kind(base_ret) == CBM_TYPE_NAMED) {+ if (base_ret->kind == CBM_TYPE_NAMED) {const CBMType** final_targs = (const CBMType**)cbm_arena_alloc(ctx->arena, (targ_count + 1) * sizeof(const CBMType*));for (int i = 0; i < targ_count; i++) final_targs[i] = targs[i];@@ -1546,7 +1546,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {// Get the base return type from the function signatureconst CBMType* base_ret = NULL;- if (safe_kind(f->signature) == CBM_TYPE_FUNC &&+ if (f->signature->kind == CBM_TYPE_FUNC &&f->signature->data.func.return_types &&f->signature->data.func.return_types[0]) {base_ret = f->signature->data.func.return_types[0];@@ -1625,19 +1625,19 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {const CBMType* func_type = c_eval_expr_type(ctx, func_node);if (!func_type) return cbm_type_unknown();// FUNC type -> return its return type- if (safe_kind(func_type) == CBM_TYPE_FUNC &&+ if (func_type->kind == CBM_TYPE_FUNC &&func_type->data.func.return_types && func_type->data.func.return_types[0]) {const CBMType* ret = func_type->data.func.return_types[0];// Template param substitution: try receiver's template args (method calls)// then try TAD from call-site argument types (free function calls)- bool needs_subst = (safe_kind(ret) == CBM_TYPE_TYPE_PARAM ||- safe_kind(ret) == CBM_TYPE_NAMED ||- safe_kind(ret) == CBM_TYPE_POINTER ||- safe_kind(ret) == CBM_TYPE_REFERENCE ||- safe_kind(ret) == CBM_TYPE_RVALUE_REF ||- safe_kind(ret) == CBM_TYPE_TEMPLATE ||- safe_kind(ret) == CBM_TYPE_SLICE);+ bool needs_subst = (ret->kind == CBM_TYPE_TYPE_PARAM ||+ ret->kind == CBM_TYPE_NAMED ||+ ret->kind == CBM_TYPE_POINTER ||+ ret->kind == CBM_TYPE_REFERENCE ||+ ret->kind == CBM_TYPE_RVALUE_REF ||+ ret->kind == CBM_TYPE_TEMPLATE ||+ ret->kind == CBM_TYPE_SLICE);if (needs_subst) {bool substituted = false;@@ -1650,7 +1650,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {// Use false to preserve TEMPLATE type — we need template args// for substitution, not the pointed-to type from operator->obj_type = c_simplify_type(ctx, obj_type, false);- if (obj_type && safe_kind(obj_type) == CBM_TYPE_TEMPLATE &&+ if (obj_type && obj_type->kind == CBM_TYPE_TEMPLATE &&obj_type->data.template_type.template_args) {// Use registered type_param_names if availableTSNode field_node = ts_node_child_by_field_name(func_node, "field", 5);@@ -1715,7 +1715,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {}if (rf && rf->type_param_names && rf->signature &&- safe_kind(rf->signature) == CBM_TYPE_FUNC &&+ rf->signature->kind == CBM_TYPE_FUNC &&rf->signature->data.func.param_types) {// Deduce: match call-site arg types against param types// to bind type_param_names@@ -1734,22 +1734,22 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {if (cbm_type_is_unknown(arg_t)) { pi++; continue; }// Unwrap ref/ptr from param typeconst CBMType* param_t = rf->signature->data.func.param_types[pi];- while (param_t && (safe_kind(param_t) == CBM_TYPE_REFERENCE ||- safe_kind(param_t) == CBM_TYPE_RVALUE_REF ||- safe_kind(param_t) == CBM_TYPE_POINTER)) {- if (safe_kind(param_t) == CBM_TYPE_POINTER) param_t = param_t->data.pointer.elem;+ while (param_t && (param_t->kind == CBM_TYPE_REFERENCE ||+ param_t->kind == CBM_TYPE_RVALUE_REF ||+ param_t->kind == CBM_TYPE_POINTER)) {+ if (param_t->kind == CBM_TYPE_POINTER) param_t = param_t->data.pointer.elem;else param_t = param_t->data.reference.elem;}// If param type is TYPE_PARAM, bind it- if (param_t && safe_kind(param_t) == CBM_TYPE_TYPE_PARAM) {+ if (param_t && param_t->kind == CBM_TYPE_TYPE_PARAM) {for (int ti = 0; ti < tp_count; ti++) {if (strcmp(rf->type_param_names[ti], param_t->data.type_param.name) == 0) {// Unwrap ref/ptr from actual arg tooconst CBMType* unwrapped = arg_t;- while (unwrapped && (safe_kind(unwrapped) == CBM_TYPE_REFERENCE ||- safe_kind(unwrapped) == CBM_TYPE_RVALUE_REF ||- safe_kind(unwrapped) == CBM_TYPE_POINTER)) {- if (safe_kind(unwrapped) == CBM_TYPE_POINTER) unwrapped = unwrapped->data.pointer.elem;+ while (unwrapped && (unwrapped->kind == CBM_TYPE_REFERENCE ||+ unwrapped->kind == CBM_TYPE_RVALUE_REF ||+ unwrapped->kind == CBM_TYPE_POINTER)) {+ if (unwrapped->kind == CBM_TYPE_POINTER) unwrapped = unwrapped->data.pointer.elem;else unwrapped = unwrapped->data.reference.elem;}if (!deduced[ti]) deduced[ti] = unwrapped;@@ -1775,13 +1775,13 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {}// Unwrap references in return type- if (safe_kind(ret) == CBM_TYPE_REFERENCE || safe_kind(ret) == CBM_TYPE_RVALUE_REF)+ if (ret->kind == CBM_TYPE_REFERENCE || ret->kind == CBM_TYPE_RVALUE_REF)ret = ret->data.reference.elem;return ret;}// Constructor call: Type(args) — if func_node resolves to a named type- if (safe_kind(func_type) == CBM_TYPE_NAMED) {+ if (func_type->kind == CBM_TYPE_NAMED) {return func_type;}@@ -1820,20 +1820,20 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {if (!arr_type) return cbm_type_unknown();// Array/slice: return element- if (safe_kind(arr_type) == CBM_TYPE_SLICE) return arr_type->data.slice.elem;- if (safe_kind(arr_type) == CBM_TYPE_POINTER) return arr_type->data.pointer.elem;+ if (arr_type->kind == CBM_TYPE_SLICE) return arr_type->data.slice.elem;+ if (arr_type->kind == CBM_TYPE_POINTER) return arr_type->data.pointer.elem;// Template with operator[]: return via method lookupconst char* qn = type_to_qn(c_simplify_type(ctx, arr_type, false));if (qn) {const CBMRegisteredFunc* op = cbm_registry_lookup_method(ctx->registry, qn, "operator[]");- if (op && op->signature && safe_kind(op->signature) == CBM_TYPE_FUNC &&+ if (op && op->signature && op->signature->kind == CBM_TYPE_FUNC &&op->signature->data.func.return_types && op->signature->data.func.return_types[0]) {const CBMType* ret = op->signature->data.func.return_types[0];- if (safe_kind(ret) == CBM_TYPE_REFERENCE) ret = ret->data.reference.elem;+ if (ret->kind == CBM_TYPE_REFERENCE) ret = ret->data.reference.elem;// Substitute template params- if (safe_kind(ret) == CBM_TYPE_TYPE_PARAM && safe_kind(arr_type) == CBM_TYPE_TEMPLATE) {+ if (ret->kind == CBM_TYPE_TYPE_PARAM && arr_type->kind == CBM_TYPE_TEMPLATE) {const char* params[] = {"T", "K", "V", NULL};const CBMType* args[3] = {NULL};int nargs = arr_type->data.template_type.arg_count;@@ -1888,10 +1888,10 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {const CBMType* inner = c_eval_expr_type(ctx, operand);inner = c_simplify_type(ctx, inner, false);// TEMPLATE with operator*(): look up and substitute return type- if (inner && safe_kind(inner) == CBM_TYPE_TEMPLATE) {+ if (inner && inner->kind == CBM_TYPE_TEMPLATE) {const char* tqn = inner->data.template_type.template_name;const CBMRegisteredFunc* opf = c_lookup_member(ctx, tqn, "operator*");- if (opf && opf->signature && safe_kind(opf->signature) == CBM_TYPE_FUNC &&+ if (opf && opf->signature && opf->signature->kind == CBM_TYPE_FUNC &&opf->signature->data.func.return_types &&opf->signature->data.func.return_types[0]) {const CBMType* ret = opf->signature->data.func.return_types[0];@@ -1914,7 +1914,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {if (na > 2) fa[2] = inner->data.template_type.template_args[2];ret = cbm_type_substitute(ctx->arena, ret, fb, fa);}- if (safe_kind(ret) == CBM_TYPE_REFERENCE)+ if (ret->kind == CBM_TYPE_REFERENCE)ret = ret->data.reference.elem;return ret;}@@ -1948,10 +1948,10 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {if (op && strcmp(op, "*") == 0) {const CBMType* inner = c_eval_expr_type(ctx, arg);inner = c_simplify_type(ctx, inner, false);- if (inner && safe_kind(inner) == CBM_TYPE_TEMPLATE) {+ if (inner && inner->kind == CBM_TYPE_TEMPLATE) {const char* tqn = inner->data.template_type.template_name;const CBMRegisteredFunc* opf = c_lookup_member(ctx, tqn, "operator*");- if (opf && opf->signature && safe_kind(opf->signature) == CBM_TYPE_FUNC &&+ if (opf && opf->signature && opf->signature->kind == CBM_TYPE_FUNC &&opf->signature->data.func.return_types &&opf->signature->data.func.return_types[0]) {const CBMType* ret = opf->signature->data.func.return_types[0];@@ -1974,7 +1974,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {if (na > 2) fa[2] = inner->data.template_type.template_args[2];ret = cbm_type_substitute(ctx->arena, ret, fb, fa);}- if (safe_kind(ret) == CBM_TYPE_REFERENCE)+ if (ret->kind == CBM_TYPE_REFERENCE)ret = ret->data.reference.elem;return ret;}@@ -2099,7 +2099,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {// co_await returns the result of operator co_await or the awaitable's await_resume// Heuristic: if operand is a template type (e.g., Task<T>), return first template argop_type = c_simplify_type(ctx, op_type, false);- if (op_type && safe_kind(op_type) == CBM_TYPE_TEMPLATE &&+ if (op_type && op_type->kind == CBM_TYPE_TEMPLATE &&op_type->data.template_type.arg_count > 0) {return op_type->data.template_type.template_args[0];}@@ -2107,7 +2107,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {const char* op_qn = type_to_qn(op_type);if (op_qn) {const CBMRegisteredFunc* ar = c_lookup_member(ctx, op_qn, "await_resume");- if (ar && ar->signature && safe_kind(ar->signature) == CBM_TYPE_FUNC &&+ if (ar && ar->signature && ar->signature->kind == CBM_TYPE_FUNC &&ar->signature->data.func.return_types &&ar->signature->data.func.return_types[0]) {return ar->signature->data.func.return_types[0];diff --git a/internal/cbm/service_patterns.c b/internal/cbm/service_patterns.cnew file mode 100644index 000000000..661df6656--- /dev/null+++ b/internal/cbm/service_patterns.c@@ -0,0 +1,372 @@+/*+ * service_patterns.c — Classify call edges by library identity in resolved QN.+ *+ * Instead of matching callee names (ambiguous: "get", "post", "send"),+ * we match library identifiers in the RESOLVED qualified name. The QN+ * contains the full module path, so import aliases are transparent:+ * r.get("/api") → QN: project.venv.requests.api.get → match "requests" → HTTP_CALLS+ *+ * Two-level matching:+ * 1. Library identifier in QN → determines edge type (HTTP/ASYNC/CONFIG)+ * 2. Method suffix → determines HTTP method (get→GET, post→POST)+ */+#include "service_patterns.h"++#include <stdbool.h>+#include <stddef.h>+#include <string.h>++/* ── Library identifier → edge type ────────────────────────────── */++typedef struct {+ const char *library_id; /* substring to find in resolved QN */+ cbm_svc_kind_t kind; /* HTTP_CALLS, ASYNC_CALLS, CONFIGURES */+ const char *broker; /* for ASYNC: broker name (NULL otherwise) */+} lib_pattern_t;++/* HTTP client libraries — match these substrings in the resolved QN.+ * Sources: github.com/easybase/awesome-http, official SDK docs, agent research */+static const lib_pattern_t http_libraries[] = {+ /* Python */+ {"requests", CBM_SVC_HTTP, NULL},+ {"httpx", CBM_SVC_HTTP, NULL},+ {"aiohttp", CBM_SVC_HTTP, NULL},+ {"urllib", CBM_SVC_HTTP, NULL},+ {"urllib3", CBM_SVC_HTTP, NULL},+ {"httplib2", CBM_SVC_HTTP, NULL},+ {"pycurl", CBM_SVC_HTTP, NULL},+ {"treq", CBM_SVC_HTTP, NULL},+ {"uplink", CBM_SVC_HTTP, NULL},++ /* JavaScript / TypeScript */+ {"axios", CBM_SVC_HTTP, NULL},+ {"superagent", CBM_SVC_HTTP, NULL},+ {"needle", CBM_SVC_HTTP, NULL},+ {"node-fetch", CBM_SVC_HTTP, NULL},+ {"undici", CBM_SVC_HTTP, NULL},+ {"ofetch", CBM_SVC_HTTP, NULL},+ {"wretch", CBM_SVC_HTTP, NULL},+ {"sindresorhus/ky", CBM_SVC_HTTP, NULL},+ {"phin", CBM_SVC_HTTP, NULL},++ /* Go */+ {"net/http", CBM_SVC_HTTP, NULL},+ {"resty", CBM_SVC_HTTP, NULL},+ {"sling", CBM_SVC_HTTP, NULL},+ {"heimdall", CBM_SVC_HTTP, NULL},+ {"gentleman", CBM_SVC_HTTP, NULL},+ {"retryablehttp", CBM_SVC_HTTP, NULL},++ /* Java / Kotlin */+ {"HttpClient", CBM_SVC_HTTP, NULL},+ {"OkHttp", CBM_SVC_HTTP, NULL},+ {"okhttp3", CBM_SVC_HTTP, NULL},+ {"RestTemplate", CBM_SVC_HTTP, NULL},+ {"WebClient", CBM_SVC_HTTP, NULL},+ {"Unirest", CBM_SVC_HTTP, NULL},+ {"AsyncHttpClient", CBM_SVC_HTTP, NULL},+ {"apache.http", CBM_SVC_HTTP, NULL},+ {"Retrofit", CBM_SVC_HTTP, NULL},+ {"Feign", CBM_SVC_HTTP, NULL},+ {"ktor.client", CBM_SVC_HTTP, NULL},+ {"kittinunf.fuel", CBM_SVC_HTTP, NULL},++ /* Rust */+ {"reqwest", CBM_SVC_HTTP, NULL},+ {"hyper", CBM_SVC_HTTP, NULL},+ {"surf", CBM_SVC_HTTP, NULL},+ {"ureq", CBM_SVC_HTTP, NULL},+ {"isahc", CBM_SVC_HTTP, NULL},+ {"attohttpc", CBM_SVC_HTTP, NULL},++ /* C# */+ {"HttpClient", CBM_SVC_HTTP, NULL},+ {"RestSharp", CBM_SVC_HTTP, NULL},+ {"Flurl", CBM_SVC_HTTP, NULL},+ {"Refit", CBM_SVC_HTTP, NULL},++ /* Ruby */+ {"HTTParty", CBM_SVC_HTTP, NULL},+ {"Faraday", CBM_SVC_HTTP, NULL},+ {"RestClient", CBM_SVC_HTTP, NULL},+ {"Typhoeus", CBM_SVC_HTTP, NULL},+ {"Excon", CBM_SVC_HTTP, NULL},+ {"Net::HTTP", CBM_SVC_HTTP, NULL},++ /* PHP */+ {"Guzzle", CBM_SVC_HTTP, NULL},+ {"guzzle", CBM_SVC_HTTP, NULL},+ {"curl", CBM_SVC_HTTP, NULL},+ {"Symfony\\HttpClient", CBM_SVC_HTTP, NULL},++ /* C/C++ */+ {"cpr", CBM_SVC_HTTP, NULL},+ {"cpp-httplib", CBM_SVC_HTTP, NULL},+ {"Poco.Net", CBM_SVC_HTTP, NULL},+ {"Beast", CBM_SVC_HTTP, NULL},++ /* Swift */+ {"Alamofire", CBM_SVC_HTTP, NULL},+ {"Moya", CBM_SVC_HTTP, NULL},+ {"URLSession", CBM_SVC_HTTP, NULL},++ /* Dart */+ {"Dio", CBM_SVC_HTTP, NULL},+ {"dio", CBM_SVC_HTTP, NULL},+ {"package:http", CBM_SVC_HTTP, NULL},+ {"Chopper", CBM_SVC_HTTP, NULL},++ /* Elixir */+ {"HTTPoison", CBM_SVC_HTTP, NULL},+ {"Tesla", CBM_SVC_HTTP, NULL},+ {"Finch", CBM_SVC_HTTP, NULL},+ {"Mint.HTTP", CBM_SVC_HTTP, NULL},++ /* Scala */+ {"sttp", CBM_SVC_HTTP, NULL},+ {"akka.http", CBM_SVC_HTTP, NULL},+ {"http4s", CBM_SVC_HTTP, NULL},+ {"scalaj", CBM_SVC_HTTP, NULL},++ /* Haskell */+ {"wreq", CBM_SVC_HTTP, NULL},+ {"http-client", CBM_SVC_HTTP, NULL},+ {"http-conduit", CBM_SVC_HTTP, NULL},+ {"servant-client", CBM_SVC_HTTP, NULL},+ {"Network.HTTP", CBM_SVC_HTTP, NULL},++ /* Lua */+ {"socket.http", CBM_SVC_HTTP, NULL},+ {"resty.http", CBM_SVC_HTTP, NULL},++ {NULL, CBM_SVC_NONE, NULL},+};++/* Async dispatch / message broker libraries */+static const lib_pattern_t async_libraries[] = {+ /* GCP */+ {"cloudtasks", CBM_SVC_ASYNC, "cloud_tasks"},+ {"cloud_tasks", CBM_SVC_ASYNC, "cloud_tasks"},+ {"cloud.tasks", CBM_SVC_ASYNC, "cloud_tasks"},+ {"CloudTasks", CBM_SVC_ASYNC, "cloud_tasks"},+ {"pubsub", CBM_SVC_ASYNC, "pubsub"},+ {"cloud.pubsub", CBM_SVC_ASYNC, "pubsub"},+ {"PubSub", CBM_SVC_ASYNC, "pubsub"},++ /* AWS — use SDK module paths to avoid false positives */+ {"aws-sdk-go/service/sqs", CBM_SVC_ASYNC, "sqs"},+ {"aws_sdk_sqs", CBM_SVC_ASYNC, "sqs"},+ {"Amazon.SQS", CBM_SVC_ASYNC, "sqs"},+ {"@aws-sdk/client-sqs", CBM_SVC_ASYNC, "sqs"},+ {"boto3.client.sqs", CBM_SVC_ASYNC, "sqs"},+ {"aws-sdk-go/service/sns", CBM_SVC_ASYNC, "sns"},+ {"aws_sdk_sns", CBM_SVC_ASYNC, "sns"},+ {"Amazon.SNS", CBM_SVC_ASYNC, "sns"},+ {"@aws-sdk/client-sns", CBM_SVC_ASYNC, "sns"},+ {"eventbridge", CBM_SVC_ASYNC, "eventbridge"},+ {"EventBridge", CBM_SVC_ASYNC, "eventbridge"},+ {"aws-sdk-go/service/lambda", CBM_SVC_ASYNC, "lambda"},+ {"aws_sdk_lambda", CBM_SVC_ASYNC, "lambda"},+ {"@aws-sdk/client-lambda", CBM_SVC_ASYNC, "lambda"},+ {"stepfunctions", CBM_SVC_ASYNC, "stepfunctions"},++ /* Azure */+ {"ServiceBus", CBM_SVC_ASYNC, "servicebus"},+ {"Azure.Messaging", CBM_SVC_ASYNC, "servicebus"},++ /* Kafka */+ {"kafka", CBM_SVC_ASYNC, "kafka"},+ {"Kafka", CBM_SVC_ASYNC, "kafka"},+ {"kafkajs", CBM_SVC_ASYNC, "kafka"},+ {"sarama", CBM_SVC_ASYNC, "kafka"},+ {"rdkafka", CBM_SVC_ASYNC, "kafka"},+ {"confluent", CBM_SVC_ASYNC, "kafka"},+ {"Confluent.Kafka", CBM_SVC_ASYNC, "kafka"},++ /* RabbitMQ */+ {"amqp", CBM_SVC_ASYNC, "rabbitmq"},+ {"AMQP", CBM_SVC_ASYNC, "rabbitmq"},+ {"amqplib", CBM_SVC_ASYNC, "rabbitmq"},+ {"RabbitMQ", CBM_SVC_ASYNC, "rabbitmq"},+ {"lapin", CBM_SVC_ASYNC, "rabbitmq"},+ {"MassTransit", CBM_SVC_ASYNC, "rabbitmq"},++ /* NATS */+ {"nats", CBM_SVC_ASYNC, "nats"},+ {"NATS", CBM_SVC_ASYNC, "nats"},++ /* Redis pub/sub */+ {"ioredis", CBM_SVC_ASYNC, "redis"},++ /* Task queues */+ {"celery", CBM_SVC_ASYNC, "celery"},+ {"Celery", CBM_SVC_ASYNC, "celery"},+ {"dramatiq", CBM_SVC_ASYNC, "dramatiq"},+ {"huey", CBM_SVC_ASYNC, "huey"},+ {"python-rq", CBM_SVC_ASYNC, "rq"},+ {"rq.Queue", CBM_SVC_ASYNC, "rq"},+ {"bullmq", CBM_SVC_ASYNC, "bullmq"},+ {"BullMQ", CBM_SVC_ASYNC, "bullmq"},+ {"bull.Queue", CBM_SVC_ASYNC, "bull"},+ {"Sidekiq", CBM_SVC_ASYNC, "sidekiq"},+ {"sidekiq", CBM_SVC_ASYNC, "sidekiq"},+ {"Resque", CBM_SVC_ASYNC, "resque"},+ {"GoodJob", CBM_SVC_ASYNC, "goodjob"},+ {"DelayedJob", CBM_SVC_ASYNC, "delayed_job"},+ {"Hangfire", CBM_SVC_ASYNC, "hangfire"},+ {"NServiceBus", CBM_SVC_ASYNC, "nservicebus"},+ {"asynq", CBM_SVC_ASYNC, "asynq"},+ {"RichardKnop/machinery", CBM_SVC_ASYNC, "machinery"},++ /* Workflow engines — use specific module paths to avoid "Temporal" in Django etc. */+ {"temporalio", CBM_SVC_ASYNC, "temporal"},+ {"@temporalio", CBM_SVC_ASYNC, "temporal"},+ {"temporal.client", CBM_SVC_ASYNC, "temporal"},+ {"temporal.worker", CBM_SVC_ASYNC, "temporal"},+ {"inngest", CBM_SVC_ASYNC, "inngest"},++ /* Elixir */+ {"Oban", CBM_SVC_ASYNC, "oban"},+ {"Broadway", CBM_SVC_ASYNC, "broadway"},+ {"GenStage", CBM_SVC_ASYNC, "genstage"},+ {"Phoenix.PubSub", CBM_SVC_ASYNC, "phoenix_pubsub"},++ /* Scala */+ {"Alpakka", CBM_SVC_ASYNC, "alpakka"},++ {NULL, CBM_SVC_NONE, NULL},+};++/* Config accessor libraries */+static const lib_pattern_t config_libraries[] = {+ /* Universal */+ {"getenv", CBM_SVC_CONFIG, NULL},+ {"Getenv", CBM_SVC_CONFIG, NULL},+ {"getEnv", CBM_SVC_CONFIG, NULL},+ {"LookupEnv", CBM_SVC_CONFIG, NULL},+ {"lookupEnv", CBM_SVC_CONFIG, NULL},+ {"get_env", CBM_SVC_CONFIG, NULL},+ {"fetch_env", CBM_SVC_CONFIG, NULL},+ {"GetEnvironmentVariable", CBM_SVC_CONFIG, NULL},+ {"getProperty", CBM_SVC_CONFIG, NULL},+ {"getEnvironment", CBM_SVC_CONFIG, NULL},++ /* Go */+ {"viper", CBM_SVC_CONFIG, NULL},+ {"envconfig", CBM_SVC_CONFIG, NULL},+ {"godotenv", CBM_SVC_CONFIG, NULL},++ /* Python */+ {"decouple", CBM_SVC_CONFIG, NULL},+ {"dynaconf", CBM_SVC_CONFIG, NULL},+ {"dotenv", CBM_SVC_CONFIG, NULL},++ /* JS/TS */+ {"nconf", CBM_SVC_CONFIG, NULL},+ {"convict", CBM_SVC_CONFIG, NULL},+ {"envalid", CBM_SVC_CONFIG, NULL},++ /* Rust */+ {"dotenvy", CBM_SVC_CONFIG, NULL},+ {"figment", CBM_SVC_CONFIG, NULL},+ {"config-rs", CBM_SVC_CONFIG, NULL},++ /* Java/Scala */+ {"ConfigFactory", CBM_SVC_CONFIG, NULL},+ {"ConfigurationProperties", CBM_SVC_CONFIG, NULL},++ /* Elixir */+ {"Application.get_env", CBM_SVC_CONFIG, NULL},+ {"Application.fetch_env", CBM_SVC_CONFIG, NULL},++ {NULL, CBM_SVC_NONE, NULL},+};++/* ── HTTP method inference from function/method name suffix ───── */++typedef struct {+ const char *suffix;+ const char *method;+} method_suffix_t;++static const method_suffix_t method_suffixes[] = {+ {".get", "GET"}, {".Get", "GET"}, {".GET", "GET"},+ {".post", "POST"}, {".Post", "POST"}, {".POST", "POST"},+ {".put", "PUT"}, {".Put", "PUT"}, {".PUT", "PUT"},+ {".delete", "DELETE"}, {".Delete", "DELETE"}, {".DELETE", "DELETE"},+ {".patch", "PATCH"}, {".Patch", "PATCH"}, {".PATCH", "PATCH"},+ {".head", "HEAD"}, {".Head", "HEAD"}, {".HEAD", "HEAD"},+ {".options", "OPTIONS"}, {".Options", "OPTIONS"}, {"GetAsync", "GET"},+ {"PostAsync", "POST"}, {"PutAsync", "PUT"}, {"DeleteAsync", "DELETE"},+ {"SendAsync", NULL}, {"getForObject", "GET"}, {"getForEntity", "GET"},+ {"postForObject", "POST"}, {"postForEntity", "POST"}, {NULL, NULL},+};++/* ── Matching implementation ───────────────────────────────────── */++/* Check if any library identifier appears as a substring in the QN.+ * Case-sensitive: "requests" matches "project.venv.requests.api.get"+ * but not "Requests". Library names are specific enough to avoid+ * false positives even with substring matching. */+static const lib_pattern_t *match_qn(const char *qn, const lib_pattern_t *patterns) {+ if (!qn || !qn[0]) {+ return NULL;+ }+ for (int i = 0; patterns[i].library_id != NULL; i++) {+ if (strstr(qn, patterns[i].library_id) != NULL) {+ return &patterns[i];+ }+ }+ return NULL;+}++/* ── Public API ────────────────────────────────────────────────── */++void cbm_service_patterns_init(void) {+ /* No-op — tables are static const */+}++cbm_svc_kind_t cbm_service_pattern_match(const char *resolved_qn) {+ if (!resolved_qn || !resolved_qn[0]) {+ return CBM_SVC_NONE;+ }++ const lib_pattern_t *p = match_qn(resolved_qn, http_libraries);+ if (p) {+ return p->kind;+ }++ p = match_qn(resolved_qn, async_libraries);+ if (p) {+ return p->kind;+ }++ p = match_qn(resolved_qn, config_libraries);+ if (p) {+ return p->kind;+ }++ return CBM_SVC_NONE;+}++const char *cbm_service_pattern_http_method(const char *callee_name) {+ if (!callee_name) {+ return NULL;+ }+ for (int i = 0; method_suffixes[i].suffix != NULL; i++) {+ size_t slen = strlen(method_suffixes[i].suffix);+ size_t clen = strlen(callee_name);+ if (clen >= slen && strcmp(callee_name + clen - slen, method_suffixes[i].suffix) == 0) {+ return method_suffixes[i].method;+ }+ }+ return NULL;+}++const char *cbm_service_pattern_broker(const char *resolved_qn) {+ if (!resolved_qn) {+ return NULL;+ }+ const lib_pattern_t *p = match_qn(resolved_qn, async_libraries);+ return p ? p->broker : NULL;+}diff --git a/internal/cbm/service_patterns.h b/internal/cbm/service_patterns.hnew file mode 100644index 000000000..adff9a72d--- /dev/null+++ b/internal/cbm/service_patterns.h@@ -0,0 +1,39 @@+/*+ * service_patterns.h — Allowlists for HTTP clients, async dispatch, and config accessors.+ *+ * Used during call resolution to classify CALLS edges as:+ * HTTP_CALLS — synchronous HTTP client calls+ * ASYNC_CALLS — async message/task dispatch+ * CONFIGURES — config/env access+ *+ * Lookup is O(1) via hash table initialized once at startup.+ */+#ifndef CBM_SERVICE_PATTERNS_H+#define CBM_SERVICE_PATTERNS_H++/* Edge type returned by pattern match. */+typedef enum {+ CBM_SVC_NONE = 0, /* Not a service pattern — use normal CALLS */+ CBM_SVC_HTTP = 1, /* Synchronous HTTP client call */+ CBM_SVC_ASYNC = 2, /* Async dispatch (message broker, task queue) */+ CBM_SVC_CONFIG = 3, /* Config/env accessor */+} cbm_svc_kind_t;++/* Initialize the pattern lookup tables. Call once at startup. Thread-safe after init. */+void cbm_service_patterns_init(void);++/* Check if a resolved QN contains a known service library identifier.+ * Returns the pattern kind, or CBM_SVC_NONE if no match.+ * Matches on library name substrings in the QN (e.g., "requests" in+ * "project.venv.requests.api.get"). Import-alias transparent. */+cbm_svc_kind_t cbm_service_pattern_match(const char *resolved_qn);++/* Get the HTTP method from the callee name suffix (e.g., ".get" → "GET").+ * Returns NULL if method cannot be inferred. */+const char *cbm_service_pattern_http_method(const char *callee_name);++/* Get the broker name for an async QN (e.g., "pubsub" from a Pub/Sub QN).+ * Returns NULL if not an async pattern. */+const char *cbm_service_pattern_broker(const char *resolved_qn);++#endif /* CBM_SERVICE_PATTERNS_H */diff --git a/scripts/clone-bench-repos.sh b/scripts/clone-bench-repos.shindex 1361273a1..883e0788c 100755--- a/scripts/clone-bench-repos.sh+++ b/scripts/clone-bench-repos.sh@@ -33,60 +33,61 @@ symlink() {mkdir -p "$BENCH_DIR"# Programming languages — Tier 1 (44 languages)-clone go "go-chi/chi"-clone python "httpie/cli"-clone javascript "expressjs/express"-clone typescript "trpc/trpc"-clone tsx "shadcn-ui/ui"-clone java "spring-projects/spring-petclinic"-clone kotlin "JetBrains/Exposed"-clone scala "playframework/play-samples"-clone rust "meilisearch/meilisearch"-clone c "redis/redis"-clone cpp "google/leveldb"-clone csharp "ardalis/CleanArchitecture"-clone php "koel/koel"-clone ruby "sinatra/sinatra"-clone lua "awesomeWM/awesome"-clone bash "bash-it/bash-it"-clone zig "tigerbeetle/tigerbeetle"-clone haskell "jgm/pandoc"-clone ocaml "ocaml/dune"-clone elixir "plausible/analytics"-clone erlang "ninenines/cowboy"-clone objc "AFNetworking/AFNetworking"-clone swift "Alamofire/Alamofire"-clone dart "felangel/bloc"-clone perl "mojolicious/mojo"-clone groovy "spockframework/spock"-clone r "tidyverse/dplyr"-clone clojure "clojure/clojure"-clone fsharp "giraffe-fsharp/Giraffe"-clone julia "SciML/DifferentialEquations.jl"-clone vimscript "SpaceVim/SpaceVim"-clone nix "NixOS/nixpkgs"-clone commonlisp "lem-project/lem"-clone elm "elm/compiler"-clone fortran "cp2k/cp2k"-clone cobol "OCamlPro/gnucobol"-clone verilog "YosysHQ/yosys"-clone emacslisp "emacs-mirror/emacs"-clone matlab "acristoffers/tree-sitter-matlab"-clone lean "leanprover-community/mathlib4"-clone form "vermaseren/form"-clone wolfram "WolframResearch/WolframLanguageForJupyter"+# Target: 100K+ LOC per repo for meaningful performance benchmarks+clone go "kubernetes/kubernetes" # 3.5M LOC, the Go benchmark+clone python "django/django" # 350K+ LOC, web framework+clone javascript "vercel/next.js" # 500K+ LOC, React framework+clone typescript "microsoft/TypeScript" # 1M+ LOC, the TS compiler+clone tsx "shadcn-ui/ui" # 728K LOC (already large)+clone java "elastic/elasticsearch" # 2M+ LOC, search engine+clone kotlin "JetBrains/Exposed" # 977K LOC (already large)+clone scala "apache/spark" # 1M+ LOC, big data+clone rust "meilisearch/meilisearch" # 409K LOC (already large)+clone c "redis/redis" # 546K LOC (already large)+clone cpp "protocolbuffers/protobuf" # 500K+ LOC, real .cpp files+clone csharp "dotnet/runtime" # Massive C# runtime+clone php "koel/koel" # 189K LOC (OK)+clone ruby "rails/rails" # 500K+ LOC, the Ruby framework+clone lua "neovim/neovim" # 500K+ LOC, editor+clone bash "ohmyzsh/ohmyzsh" # 100K+ .sh files+clone zig "tigerbeetle/tigerbeetle" # 224K LOC (already large)+clone haskell "jgm/pandoc" # 433K LOC (already large)+clone ocaml "ocaml/dune" # 345K LOC (already large)+clone elixir "plausible/analytics" # 677K LOC (already large)+clone erlang "emqx/emqx" # 500K+ LOC, MQTT broker+clone objc "realm/realm-cocoa" # 200K+ LOC, database SDK+clone swift "Alamofire/Alamofire" # 370K LOC (already large)+clone dart "felangel/bloc" # 285K LOC (already large)+clone perl "movabletype/movabletype" # 300K+ LOC, CMS+clone groovy "spockframework/spock" # 137K LOC (OK)+clone r "tidyverse/ggplot2" # 150K+ LOC, visualization+clone clojure "clojure/clojure" # 108K LOC (OK)+clone fsharp "dotnet/fsharp" # 500K+ LOC, the F# compiler+clone julia "JuliaLang/julia" # 1M+ LOC, the Julia runtime+clone vimscript "SpaceVim/SpaceVim" # 2.6M LOC (already huge)+clone nix "NixOS/nixpkgs" # 6M LOC (already huge)+clone commonlisp "lem-project/lem" # 1.2M LOC (already large)+clone elm "elm/compiler" # 57K LOC (largest Elm repo available)+clone fortran "cp2k/cp2k" # 5.9M LOC (already huge)+clone cobol "OCamlPro/gnucobol" # 540K LOC (already large)+clone verilog "YosysHQ/yosys" # 517K LOC (already large)+clone emacslisp "emacs-mirror/emacs" # 5.3M LOC (already huge)+clone matlab "acristoffers/tree-sitter-matlab" # 133K LOC (best available)+clone lean "leanprover-community/mathlib4" # 2.3M LOC (already huge)+clone form "vermaseren/form" # 221K LOC (already large)+clone wolfram "WolframResearch/WolframLanguageForJupyter" # 4K LOC (largest public Wolfram repo)# Helper languages — Tier 2 (22 languages)-clone yaml "kubernetes/examples"-clone hcl "terraform-aws-modules/terraform-aws-eks"-clone scss "twbs/bootstrap"-clone dockerfile "docker-library/official-images"-clone cmake "Kitware/CMake"-clone protobuf "googleapis/googleapis"-clone graphql "graphql/graphql-spec"-clone vue "vuejs/vue"-clone svelte "sveltejs/svelte"-clone meson "mesonbuild/meson"+clone yaml "kubernetes/examples" # K8s manifests+clone hcl "hashicorp/terraform-provider-aws" # 1M+ LOC, massive HCL+clone scss "twbs/bootstrap" # 120K LOC (OK)+clone dockerfile "docker-library/official-images" # Docker configs+clone cmake "Kitware/CMake" # 1.7M LOC (already huge)+clone protobuf "googleapis/googleapis" # 2.2M LOC (already huge)+clone graphql "graphql/graphql-spec" # 23K LOC (largest pure GraphQL)+clone vue "vuejs/core" # 200K+ LOC, Vue 3 core+clone svelte "sveltejs/svelte" # 267K LOC (already large)+clone meson "mesonbuild/meson" # 237K LOC (already large)# Shared repos (symlinked — language uses same repo as primary)symlink html javascript # Express views contain HTMLdiff --git a/src/graph_buffer/graph_buffer.c b/src/graph_buffer/graph_buffer.cindex adb35329b..bf48b426d 100644--- a/src/graph_buffer/graph_buffer.c+++ b/src/graph_buffer/graph_buffer.c@@ -15,6 +15,7 @@#include "foundation/compat.h"#include "foundation/log.h"#include "foundation/dyn_array.h"+#include <sqlite3.h>#include <stdatomic.h>#include <stdint.h> // int64_t@@ -506,6 +507,253 @@ int cbm_gbuf_delete_by_label(cbm_gbuf_t *gb, const char *label) {return 0;}+int cbm_gbuf_delete_by_file(cbm_gbuf_t *gb, const char *file_path) {+ if (!gb || !file_path) {+ return -1;+ }++ /* Collect IDs of nodes in this file */+ CBMHashTable *deleted_set = cbm_ht_create(64);+ int deleted_count = 0;+ int scanned = 0;++ for (int i = 0; i < gb->nodes.count; i++) {+ cbm_gbuf_node_t *n = gb->nodes.items[i];+ scanned++;+ if (!n->file_path || strcmp(n->file_path, file_path) != 0) {+ continue;+ }+ if (!n->qualified_name || !cbm_ht_get(gb->node_by_qn, n->qualified_name)) {+ continue;+ }++ char id_buf[32];+ make_id_key(id_buf, sizeof(id_buf), n->id);+ cbm_ht_set(deleted_set, strdup(id_buf), (void *)1);++ /* Remove from label index */+ node_ptr_array_t *label_arr = cbm_ht_get(gb->nodes_by_label, n->label);+ if (label_arr) {+ for (int j = 0; j < label_arr->count; j++) {+ if (label_arr->items[j]->id == n->id) {+ label_arr->items[j] = label_arr->items[--label_arr->count];+ break;+ }+ }+ }++ /* Remove from name index */+ node_ptr_array_t *name_arr = cbm_ht_get(gb->nodes_by_name, n->name);+ if (name_arr) {+ for (int j = 0; j < name_arr->count; j++) {+ if (name_arr->items[j]->id == n->id) {+ name_arr->items[j] = name_arr->items[--name_arr->count];+ break;+ }+ }+ }++ cbm_ht_delete(gb->node_by_qn, n->qualified_name);+ const char *stored_key = cbm_ht_get_key(gb->node_by_id, id_buf);+ cbm_ht_delete(gb->node_by_id, id_buf);+ free((void *)stored_key);++ /* NULL out QN so dump's liveness check (cbm_ht_get by QN) fails+ * even if a new node with the same QN is inserted later via merge. */+ free(n->qualified_name);+ n->qualified_name = NULL;+ deleted_count++;+ }++ if (deleted_count == 0) {+ cbm_ht_free(deleted_set);+ return 0;+ }++ /* Cascade-delete edges referencing deleted nodes */+ int write_idx = 0;+ for (int i = 0; i < gb->edges.count; i++) {+ cbm_gbuf_edge_t *e = gb->edges.items[i];+ char src_id[32];+ char tgt_id[32];+ make_id_key(src_id, sizeof(src_id), e->source_id);+ make_id_key(tgt_id, sizeof(tgt_id), e->target_id);++ if (cbm_ht_get(deleted_set, src_id) || cbm_ht_get(deleted_set, tgt_id)) {+ char key[EDGE_KEY_BUF];+ make_edge_key(key, sizeof(key), e->source_id, e->target_id, e->type);+ const char *ekey = cbm_ht_get_key(gb->edge_by_key, key);+ cbm_ht_delete(gb->edge_by_key, key);+ free((void *)ekey);++ make_src_type_key(key, sizeof(key), e->source_id, e->type);+ edge_ptr_array_t *st = cbm_ht_get(gb->edges_by_source_type, key);+ if (st) {+ for (int j = 0; j < st->count; j++) {+ if (st->items[j]->id == e->id) {+ st->items[j] = st->items[--st->count];+ break;+ }+ }+ }++ make_src_type_key(key, sizeof(key), e->target_id, e->type);+ edge_ptr_array_t *tt = cbm_ht_get(gb->edges_by_target_type, key);+ if (tt) {+ for (int j = 0; j < tt->count; j++) {+ if (tt->items[j]->id == e->id) {+ tt->items[j] = tt->items[--tt->count];+ break;+ }+ }+ }++ edge_ptr_array_t *bt = cbm_ht_get(gb->edges_by_type, e->type);+ if (bt) {+ for (int j = 0; j < bt->count; j++) {+ if (bt->items[j]->id == e->id) {+ bt->items[j] = bt->items[--bt->count];+ break;+ }+ }+ }++ free_edge_strings(e);+ free(e);+ } else {+ gb->edges.items[write_idx++] = gb->edges.items[i];+ }+ }+ gb->edges.count = write_idx;++ cbm_ht_foreach(deleted_set, free_key_only, NULL);+ cbm_ht_free(deleted_set);+ {+ char s_buf[16];+ char d_buf[16];+ snprintf(s_buf, sizeof(s_buf), "%d", scanned);+ snprintf(d_buf, sizeof(d_buf), "%d", deleted_count);+ cbm_log_info("gbuf.delete_by_file", "file", file_path, "scanned", s_buf, "deleted", d_buf);+ }+ return deleted_count;+}++int cbm_gbuf_load_from_db(cbm_gbuf_t *gb, const char *db_path, const char *project) {+ if (!gb || !db_path || !project) {+ return -1;+ }++ cbm_store_t *store = cbm_store_open_path(db_path);+ if (!store) {+ return -1;+ }++ sqlite3 *db = cbm_store_get_db(store);+ if (!db) {+ cbm_store_close(store);+ return -1;+ }++ /* First pass: find max node ID for mapping array */+ sqlite3_stmt *stmt = NULL;+ if (sqlite3_prepare_v2(db, "SELECT MAX(id) FROM nodes WHERE project = ?", -1, &stmt, NULL) !=+ SQLITE_OK) {+ cbm_store_close(store);+ return -1;+ }+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_STATIC);+ int64_t max_old_id = 0;+ if (sqlite3_step(stmt) == SQLITE_ROW) {+ max_old_id = sqlite3_column_int64(stmt, 0);+ }+ sqlite3_finalize(stmt);++ int64_t *old_to_new = calloc((size_t)(max_old_id + 1), sizeof(int64_t));+ if (!old_to_new) {+ cbm_store_close(store);+ return -1;+ }++ /* Load all nodes */+ if (sqlite3_prepare_v2(+ db,+ "SELECT id, label, name, qualified_name, file_path, start_line, end_line, properties "+ "FROM nodes WHERE project = ? ORDER BY id",+ -1, &stmt, NULL) != SQLITE_OK) {+ free(old_to_new);+ cbm_store_close(store);+ return -1;+ }+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_STATIC);++ while (sqlite3_step(stmt) == SQLITE_ROW) {+ int64_t old_id = sqlite3_column_int64(stmt, 0);+ const char *label = (const char *)sqlite3_column_text(stmt, 1);+ const char *name = (const char *)sqlite3_column_text(stmt, 2);+ const char *qn = (const char *)sqlite3_column_text(stmt, 3);+ const char *fp = (const char *)sqlite3_column_text(stmt, 4);+ int sl = sqlite3_column_int(stmt, 5);+ int el = sqlite3_column_int(stmt, 6);+ const char *props = (const char *)sqlite3_column_text(stmt, 7);++ int64_t new_id = cbm_gbuf_upsert_node(gb, label, name, qn, fp, sl, el, props);+ if (new_id > 0 && old_id <= max_old_id) {+ old_to_new[old_id] = new_id;+ }+ }+ sqlite3_finalize(stmt);++ /* Load all edges, remap IDs */+ if (sqlite3_prepare_v2(db,+ "SELECT source_id, target_id, type, properties "+ "FROM edges WHERE project = ?",+ -1, &stmt, NULL) != SQLITE_OK) {+ free(old_to_new);+ cbm_store_close(store);+ return -1;+ }+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_STATIC);++ while (sqlite3_step(stmt) == SQLITE_ROW) {+ int64_t old_src = sqlite3_column_int64(stmt, 0);+ int64_t old_tgt = sqlite3_column_int64(stmt, 1);+ const char *type = (const char *)sqlite3_column_text(stmt, 2);+ const char *props = (const char *)sqlite3_column_text(stmt, 3);++ int64_t new_src = (old_src <= max_old_id) ? old_to_new[old_src] : 0;+ int64_t new_tgt = (old_tgt <= max_old_id) ? old_to_new[old_tgt] : 0;+ if (new_src > 0 && new_tgt > 0) {+ cbm_gbuf_insert_edge(gb, new_src, new_tgt, type, props);+ }+ }+ sqlite3_finalize(stmt);++ free(old_to_new);+ cbm_store_close(store);+ return 0;+}++void cbm_gbuf_foreach_node(const cbm_gbuf_t *gb, cbm_gbuf_node_visitor_fn fn, void *userdata) {+ if (!gb || !fn) {+ return;+ }+ for (int i = 0; i < gb->nodes.count; i++) {+ const cbm_gbuf_node_t *n = gb->nodes.items[i];+ if (n->qualified_name && cbm_ht_get(gb->node_by_qn, n->qualified_name)) {+ fn(n, userdata);+ }+ }+}++void cbm_gbuf_foreach_edge(const cbm_gbuf_t *gb, cbm_gbuf_edge_visitor_fn fn, void *userdata) {+ if (!gb || !fn) {+ return;+ }+ for (int i = 0; i < gb->edges.count; i++) {+ fn(gb->edges.items[i], userdata);+ }+}+/* ── Edge operations ─────────────────────────────────────────────── */int64_t cbm_gbuf_insert_edge(cbm_gbuf_t *gb, int64_t source_id, int64_t target_id, const char *type,@@ -866,7 +1114,7 @@ int cbm_gbuf_dump_to_sqlite(cbm_gbuf_t *gb, const char *path) {int live_count = 0;for (int i = 0; i < gb->nodes.count; i++) {cbm_gbuf_node_t *n = gb->nodes.items[i];- if (cbm_ht_get(gb->node_by_qn, n->qualified_name)) {+ if (n->qualified_name && cbm_ht_get(gb->node_by_qn, n->qualified_name)) {live_count++;}}@@ -885,7 +1133,7 @@ int cbm_gbuf_dump_to_sqlite(cbm_gbuf_t *gb, const char *path) {for (int i = 0; i < gb->nodes.count; i++) {cbm_gbuf_node_t *n = gb->nodes.items[i];- if (!cbm_ht_get(gb->node_by_qn, n->qualified_name)) {+ if (!n->qualified_name || !cbm_ht_get(gb->node_by_qn, n->qualified_name)) {continue;}@@ -1037,7 +1285,7 @@ int cbm_gbuf_flush_to_store(cbm_gbuf_t *gb, cbm_store_t *store) {cbm_gbuf_node_t *n = gb->nodes.items[i];/* Skip if deleted from QN index */- if (!cbm_ht_get(gb->node_by_qn, n->qualified_name)) {+ if (!n->qualified_name || !cbm_ht_get(gb->node_by_qn, n->qualified_name)) {continue;}@@ -1099,7 +1347,7 @@ int cbm_gbuf_merge_into_store(cbm_gbuf_t *gb, cbm_store_t *store) {for (int i = 0; i < gb->nodes.count; i++) {cbm_gbuf_node_t *n = gb->nodes.items[i];- if (!cbm_ht_get(gb->node_by_qn, n->qualified_name)) {+ if (!n->qualified_name || !cbm_ht_get(gb->node_by_qn, n->qualified_name)) {continue;}diff --git a/src/graph_buffer/graph_buffer.h b/src/graph_buffer/graph_buffer.hindex eabaf1265..5daeb56a4 100644--- a/src/graph_buffer/graph_buffer.h+++ b/src/graph_buffer/graph_buffer.h@@ -102,6 +102,22 @@ void cbm_gbuf_set_next_id(cbm_gbuf_t *gb, int64_t next_id);/* Delete all nodes with a label. Cascade-deletes referencing edges. */int cbm_gbuf_delete_by_label(cbm_gbuf_t *gb, const char *label);+/* Delete all nodes for a given file path. Cascade-deletes referencing edges.+ * Used by incremental indexing to remove stale nodes before re-extraction. */+int cbm_gbuf_delete_by_file(cbm_gbuf_t *gb, const char *file_path);++/* Bulk-load all nodes and edges for a project from an existing SQLite DB+ * into this graph buffer. Returns 0 on success. */+int cbm_gbuf_load_from_db(cbm_gbuf_t *gb, const char *db_path, const char *project);++/* Iterate all live nodes (not deleted from QN index). */+typedef void (*cbm_gbuf_node_visitor_fn)(const cbm_gbuf_node_t *node, void *userdata);+void cbm_gbuf_foreach_node(const cbm_gbuf_t *gb, cbm_gbuf_node_visitor_fn fn, void *userdata);++/* Iterate all edges. */+typedef void (*cbm_gbuf_edge_visitor_fn)(const cbm_gbuf_edge_t *edge, void *userdata);+void cbm_gbuf_foreach_edge(const cbm_gbuf_t *gb, cbm_gbuf_edge_visitor_fn fn, void *userdata);+/* ── Edge operations ─────────────────────────────────────────────── *//* Insert an edge. Deduplicates by (source_id, target_id, type).diff --git a/src/pipeline/pass_calls.c b/src/pipeline/pass_calls.cindex fba1d9b29..9069de01d 100644--- a/src/pipeline/pass_calls.c+++ b/src/pipeline/pass_calls.c@@ -15,6 +15,7 @@#include "foundation/log.h"#include "foundation/compat.h"#include "cbm.h"+#include "service_patterns.h"#include "foundation/compat_regex.h"@@ -271,13 +272,87 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *filecontinue;}- /* Create CALLS edge with confidence + strategy properties */- char props[256];- snprintf(props, sizeof(props),- "{\"confidence\":%.2f,\"strategy\":\"%s\",\"candidates\":%d}", res.confidence,- res.strategy ? res.strategy : "unknown", res.candidate_count);+ /* Classify edge type by library in resolved QN */+ cbm_svc_kind_t svc = cbm_service_pattern_match(res.qualified_name);++ if (svc == CBM_SVC_HTTP || svc == CBM_SVC_ASYNC) {+ /* HTTP/async call — route through Route node for cross-service traversal.+ * Only create Route if string looks like a URL (HTTP) or topic name (async). */+ const char *url_or_topic = call->first_string_arg;+ int is_valid_url =+ (url_or_topic != NULL && url_or_topic[0] != '\0' &&+ (url_or_topic[0] == '/' || strstr(url_or_topic, "://") != NULL));+ int is_valid_topic = (url_or_topic != NULL && url_or_topic[0] != '\0' &&+ svc == CBM_SVC_ASYNC && strlen(url_or_topic) > 2);+ if (is_valid_url || is_valid_topic) {+ const char *edge_type = (svc == CBM_SVC_HTTP) ? "HTTP_CALLS" : "ASYNC_CALLS";+ const char *http_method =+ (svc == CBM_SVC_HTTP) ? cbm_service_pattern_http_method(call->callee_name)+ : NULL;+ const char *broker = (svc == CBM_SVC_ASYNC)+ ? cbm_service_pattern_broker(res.qualified_name)+ : NULL;++ /* Build Route QN: __route__METHOD__/path or __route__broker__topic */+ char route_qn[CBM_ROUTE_QN_SIZE];+ if (svc == CBM_SVC_HTTP) {+ snprintf(route_qn, sizeof(route_qn), "__route__%s__%s",+ http_method ? http_method : "ANY", url_or_topic);+ } else {+ snprintf(route_qn, sizeof(route_qn), "__route__%s__%s",+ broker ? broker : "async", url_or_topic);+ }- cbm_gbuf_insert_edge(ctx->gbuf, source_node->id, target_node->id, "CALLS", props);+ /* Create or find Route node */+ int64_t route_id = cbm_gbuf_upsert_node(+ ctx->gbuf, "Route", url_or_topic, route_qn, "", 0, 0,+ svc == CBM_SVC_HTTP ? (http_method ? http_method : "{}")+ : (broker ? broker : "{}"));++ /* Edge: caller → Route */+ char props[512];+ snprintf(props, sizeof(props),+ "{\"callee\":\"%s\",\"url_path\":\"%s\"%s%s%s%s%s}", call->callee_name,+ url_or_topic, http_method ? ",\"method\":\"" : "",+ http_method ? http_method : "", http_method ? "\"" : "",+ broker ? ",\"broker\":\"" : "", broker ? broker : "");+ if (broker) {+ /* Close the broker value quote */+ size_t plen = strlen(props);+ if (plen > 0 && props[plen - 1] != '}') {+ snprintf(props + plen - 1, sizeof(props) - plen + 1, "\"}");+ }+ }+ cbm_gbuf_insert_edge(ctx->gbuf, source_node->id, route_id, edge_type, props);+ } else {+ /* No URL/topic extracted — fall through to normal CALLS edge */+ char props[512];+ snprintf(props, sizeof(props),+ "{\"callee\":\"%s\",\"confidence\":%.2f,\"strategy\":\"%s\","+ "\"candidates\":%d}",+ call->callee_name, res.confidence,+ res.strategy ? res.strategy : "unknown", res.candidate_count);+ cbm_gbuf_insert_edge(ctx->gbuf, source_node->id, target_node->id, "CALLS",+ props);+ }+ } else if (svc == CBM_SVC_CONFIG) {+ char props[512];+ snprintf(props, sizeof(props),+ "{\"callee\":\"%s\",\"key\":\"%s\",\"confidence\":%.2f}",+ call->callee_name, call->first_string_arg ? call->first_string_arg : "",+ res.confidence);+ cbm_gbuf_insert_edge(ctx->gbuf, source_node->id, target_node->id, "CONFIGURES",+ props);+ } else {+ /* Normal CALLS edge */+ char props[512];+ snprintf(props, sizeof(props),+ "{\"callee\":\"%s\",\"confidence\":%.2f,\"strategy\":\"%s\","+ "\"candidates\":%d}",+ call->callee_name, res.confidence, res.strategy ? res.strategy : "unknown",+ res.candidate_count);+ cbm_gbuf_insert_edge(ctx->gbuf, source_node->id, target_node->id, "CALLS", props);+ }resolved++;}diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.cindex 3193c1c7e..7c22a62ee 100644--- a/src/pipeline/pass_parallel.c+++ b/src/pipeline/pass_parallel.c@@ -16,6 +16,7 @@#include "foundation/compat.h"#include "foundation/compat_thread.h"#include "graph_buffer/graph_buffer.h"+#include "service_patterns.h"// NOLINTNEXTLINE(misc-include-cleaner) — platform.h included for interface contract#include "foundation/platform.h"#include "foundation/log.h"@@ -998,6 +999,63 @@ typedef struct {_Atomic int next_file_idx;} resolve_ctx_t;+/* Classify a resolved call by library identity and emit the appropriate edge.+ * Extracted from resolve_worker to keep cognitive complexity under threshold. */+static void emit_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,+ const cbm_gbuf_node_t *target, const CBMCall *call,+ const cbm_resolution_t *res) {+ cbm_svc_kind_t svc = cbm_service_pattern_match(res->qualified_name);+ const char *arg = call->first_string_arg;++ int has_url = (arg != NULL && arg[0] != '\0' && (arg[0] == '/' || strstr(arg, "://") != NULL));+ int has_topic = (arg != NULL && arg[0] != '\0' && svc == CBM_SVC_ASYNC && strlen(arg) > 2);++ if ((svc == CBM_SVC_HTTP || svc == CBM_SVC_ASYNC) && (has_url || has_topic)) {+ const char *edge_type = (svc == CBM_SVC_HTTP) ? "HTTP_CALLS" : "ASYNC_CALLS";+ const char *method =+ (svc == CBM_SVC_HTTP) ? cbm_service_pattern_http_method(call->callee_name) : NULL;+ const char *broker =+ (svc == CBM_SVC_ASYNC) ? cbm_service_pattern_broker(res->qualified_name) : NULL;++ char route_qn[CBM_ROUTE_QN_SIZE];+ if (svc == CBM_SVC_HTTP) {+ snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", method ? method : "ANY", arg);+ } else {+ snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", broker ? broker : "async", arg);+ }++ char route_props[256];+ if (method != NULL) {+ snprintf(route_props, sizeof(route_props), "{\"method\":\"%s\"}", method);+ } else if (broker != NULL) {+ snprintf(route_props, sizeof(route_props), "{\"broker\":\"%s\"}", broker);+ } else {+ snprintf(route_props, sizeof(route_props), "{}");+ }+ int64_t route_id =+ cbm_gbuf_upsert_node(gbuf, "Route", arg, route_qn, "", 0, 0, route_props);++ char props[512];+ snprintf(props, sizeof(props), "{\"callee\":\"%s\",\"url_path\":\"%s\"%s%s%s%s%s%s}",+ call->callee_name, arg, method ? ",\"method\":\"" : "", method ? method : "",+ method ? "\"" : "", broker ? ",\"broker\":\"" : "", broker ? broker : "",+ broker ? "\"" : "");+ cbm_gbuf_insert_edge(gbuf, source->id, route_id, edge_type, props);+ } else if (svc == CBM_SVC_CONFIG) {+ char props[512];+ snprintf(props, sizeof(props), "{\"callee\":\"%s\",\"key\":\"%s\",\"confidence\":%.2f}",+ call->callee_name, arg != NULL ? arg : "", res->confidence);+ cbm_gbuf_insert_edge(gbuf, source->id, target->id, "CONFIGURES", props);+ } else {+ char props[512];+ snprintf(props, sizeof(props),+ "{\"callee\":\"%s\",\"confidence\":%.2f,\"strategy\":\"%s\",\"candidates\":%d}",+ call->callee_name, res->confidence, res->strategy ? res->strategy : "unknown",+ res->candidate_count);+ cbm_gbuf_insert_edge(gbuf, source->id, target->id, "CALLS", props);+ }+}+static void resolve_worker(int worker_id, void *ctx_ptr) {resolve_ctx_t *rc = ctx_ptr;resolve_worker_state_t *ws = &rc->workers[worker_id];@@ -1069,12 +1127,8 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {continue;}- char props[256];- snprintf(props, sizeof(props),- "{\"confidence\":%.2f,\"strategy\":\"%s\",\"candidates\":%d}", res.confidence,- res.strategy ? res.strategy : "unknown", res.candidate_count);- cbm_gbuf_insert_edge(ws->local_edge_buf, source_node->id, target_node->id, "CALLS",- props);+ /* Classify and emit edge via helper (keeps resolve_worker complexity down) */+ emit_service_edge(ws->local_edge_buf, source_node, target_node, call, &res);ws->calls_resolved++;}@@ -1109,7 +1163,11 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {continue;}- cbm_gbuf_insert_edge(ws->local_edge_buf, src->id, tgt->id, "USAGE", "{}");+ {+ char uprops[256];+ snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", usage->ref_name);+ cbm_gbuf_insert_edge(ws->local_edge_buf, src->id, tgt->id, "USAGE", uprops);+ }ws->usages_resolved++;}diff --git a/src/pipeline/pass_route_nodes.c b/src/pipeline/pass_route_nodes.cnew file mode 100644index 000000000..aec7d2eb1--- /dev/null+++ b/src/pipeline/pass_route_nodes.c@@ -0,0 +1,261 @@+/*+ * pass_route_nodes.c — Create Route nodes for HTTP_CALLS/ASYNC_CALLS edges.+ *+ * After parallel resolve merges edges into the main gbuf, HTTP_CALLS and+ * ASYNC_CALLS edges have url_path/method/broker in properties but point to+ * the library function (e.g., requests.get). This pass:+ *+ * 1. Scans all HTTP_CALLS/ASYNC_CALLS edges+ * 2. Extracts url_path from edge properties+ * 3. Creates Route nodes with deterministic QNs (__route__METHOD__/path)+ * 4. Re-targets edges from library function → Route node+ *+ * Route nodes are the rendezvous point for cross-service communication:+ * Service A: checkout() → HTTP_CALLS → Route("POST /api/orders")+ * Service B: create_order() → HANDLES → Route("POST /api/orders")+ */+#include "pipeline/pipeline_internal.h"+#include "graph_buffer/graph_buffer.h"+#include "foundation/log.h"++#include <stdio.h>+#include <string.h>++/* Extract a JSON string value by key from properties.+ * Returns pointer into buf (caller provides buffer). NULL if not found. */+static const char *json_extract(const char *json, const char *key, char *buf, int bufsz) {+ if (!json || !key) {+ return NULL;+ }+ /* Build "key":" pattern */+ char pattern[128];+ snprintf(pattern, sizeof(pattern), "\"%s\":\"", key);+ const char *start = strstr(json, pattern);+ if (!start) {+ return NULL;+ }+ start += strlen(pattern);+ const char *end = strchr(start, '"');+ if (!end || end == start) {+ return NULL;+ }+ int len = (int)(end - start);+ if (len >= bufsz) {+ len = bufsz - 1;+ }+ memcpy(buf, start, (size_t)len);+ buf[len] = '\0';+ return buf;+}++/* Visitor context for edge scanning */+typedef struct {+ cbm_gbuf_t *gb;+ int created;+} route_ctx_t;++static void route_edge_visitor(const cbm_gbuf_edge_t *edge, void *userdata) {+ route_ctx_t *ctx = (route_ctx_t *)userdata;++ /* Only process HTTP_CALLS and ASYNC_CALLS */+ if (strcmp(edge->type, "HTTP_CALLS") != 0 && strcmp(edge->type, "ASYNC_CALLS") != 0) {+ return;+ }++ /* Extract url_path from properties */+ char url_buf[512];+ const char *url = json_extract(edge->properties_json, "url_path", url_buf, sizeof(url_buf));+ if (!url || !url[0]) {+ return;+ }++ /* Extract method or broker */+ char method_buf[16];+ char broker_buf[64];+ const char *method =+ json_extract(edge->properties_json, "method", method_buf, sizeof(method_buf));+ const char *broker =+ json_extract(edge->properties_json, "broker", broker_buf, sizeof(broker_buf));++ /* Build Route QN */+ char route_qn[CBM_ROUTE_QN_SIZE];+ if (strcmp(edge->type, "HTTP_CALLS") == 0) {+ snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", method ? method : "ANY", url);+ } else {+ snprintf(route_qn, sizeof(route_qn), "__route__%s__%s", broker ? broker : "async", url);+ }++ /* Build properties for Route node */+ char route_props[256];+ if (method) {+ snprintf(route_props, sizeof(route_props), "{\"method\":\"%s\"}", method);+ } else if (broker) {+ snprintf(route_props, sizeof(route_props), "{\"broker\":\"%s\"}", broker);+ } else {+ snprintf(route_props, sizeof(route_props), "{}");+ }++ /* Create or find Route node (deduped by QN) */+ cbm_gbuf_upsert_node(ctx->gb, "Route", url, route_qn, "", 0, 0, route_props);+ ctx->created++;++ /* Note: we do NOT re-target the edge here because modifying edges during+ * iteration is unsafe. The edge stays pointing to the library function.+ * The httplink URL matching pass will create the Route→handler HANDLES+ * edge separately. The caller→Route edge is created by pass_calls for+ * the sequential path; for the parallel path, the caller→library edge+ * with url_path in properties is sufficient for query_graph to find+ * the Route via: caller → HTTP_CALLS(url_path="/api/x") + Route("/api/x"). */+}++/* Extract URL path from full URL: "https://host/path/" → "/path/" */+static const char *url_path(const char *url) {+ if (!url) {+ return NULL;+ }+ const char *scheme_end = strstr(url, "://");+ if (!scheme_end) {+ return url; /* Already a path */+ }+ const char *path = strchr(scheme_end + 3, '/');+ return path ? path : "/";+}++/* Extract service name from Cloud Run URL hostname.+ * "my-svc-ab12cd34ef-uc.a.run.app/path" → "my-svc" */+static const char *extract_service_name(const char *url, char *buf, int bufsz) {+ if (!url) {+ return NULL;+ }+ const char *scheme_end = strstr(url, "://");+ if (!scheme_end) {+ return NULL;+ }+ const char *host_start = scheme_end + 3;+ /* Service name is everything before the revision hash.+ * Pattern: service-name-HASH-HASH.region.run.app+ * Heuristic: find the longest prefix of dash-separated words+ * before a segment that looks like a hash (short alphanumeric). */+ const char *end = host_start;+ while (*end && *end != '.' && *end != '/') {+ end++;+ }+ /* Copy full hostname part before first dot */+ int hlen = (int)(end - host_start);+ if (hlen <= 0 || hlen >= bufsz) {+ return NULL;+ }++ /* Walk backward from end, stripping hash-like segments.+ * Cloud Run format: name-REVHASH-LOCHASH.region.run.app */+ char tmp[256];+ if (hlen >= (int)sizeof(tmp)) {+ return NULL;+ }+ memcpy(tmp, host_start, (size_t)hlen);+ tmp[hlen] = '\0';++ /* Cloud Run hostname format: service-name-REVHASH-LOCHASH.region.run.app+ * Strip last two dash-separated segments (revision + location hashes).+ * Hash segments are typically 2-12 alphanumeric characters. */+ for (int strip = 0; strip < 2; strip++) {+ char *last_dash = strrchr(tmp, '-');+ if (last_dash && strlen(last_dash + 1) <= 12) {+ *last_dash = '\0';+ }+ }++ snprintf(buf, (size_t)bufsz, "%s", tmp);+ return buf;+}++/* Phase 2: Match infra Route URLs to handler Route nodes by URL path + service name. */+static void match_infra_routes(cbm_gbuf_t *gb) {+ /* Collect infra Routes (from YAML) and handler Routes (from Python decorators) */+ const cbm_gbuf_node_t **all_routes = NULL;+ int route_count = 0;+ if (cbm_gbuf_find_by_label(gb, "Route", &all_routes, &route_count) != 0 || route_count == 0) {+ return;+ }++ int matched = 0;++ for (int i = 0; i < route_count; i++) {+ const cbm_gbuf_node_t *infra = all_routes[i];+ /* Only process infra routes (full URLs) */+ if (!infra->qualified_name || strncmp(infra->qualified_name, "__route__infra__", 16) != 0) {+ continue;+ }+ if (!infra->name || !strstr(infra->name, "://")) {+ continue;+ }++ const char *infra_path = url_path(infra->name);+ char svc_buf[128];+ const char *svc_name = extract_service_name(infra->name, svc_buf, sizeof(svc_buf));+ if (!infra_path || !svc_name) {+ continue;+ }++ /* Find handler Routes whose file_path contains the service name+ * and whose route path matches the infra URL path */+ for (int j = 0; j < route_count; j++) {+ const cbm_gbuf_node_t *handler_route = all_routes[j];+ /* Skip infra routes */+ if (handler_route->qualified_name &&+ strncmp(handler_route->qualified_name, "__route__", 9) == 0) {+ continue;+ }+ /* Handler route must be in the matching service directory */+ if (!handler_route->file_path || !strstr(handler_route->file_path, svc_name)) {+ continue;+ }++ /* Check if the infra URL path matches the handler route path.+ * Handler route name is like "POST /path" — extract the path part. */+ const char *handler_name = handler_route->name;+ if (!handler_name) {+ continue;+ }+ /* Skip method prefix: "POST /path" → "/path" */+ const char *handler_path = strchr(handler_name, '/');+ if (!handler_path) {+ continue;+ }++ /* Match: infra path starts with handler path or handler path contains infra path */+ if (strstr(infra_path, handler_path) != NULL ||+ strstr(handler_path, infra_path) != NULL) {+ /* Create HANDLES edge: infra Route → handler Route (connecting them) */+ cbm_gbuf_insert_edge(gb, infra->id, handler_route->id, "HANDLES",+ "{\"source\":\"infra_match\"}");+ matched++;+ break; /* One match per infra route is enough */+ }+ }+ }++ if (matched > 0) {+ char buf[16];+ snprintf(buf, sizeof(buf), "%d", matched);+ cbm_log_info("pass.route_match", "infra_matched", buf);+ }+}++void cbm_pipeline_create_route_nodes(cbm_gbuf_t *gb) {+ if (!gb) {+ return;+ }++ route_ctx_t ctx = {.gb = gb, .created = 0};+ cbm_gbuf_foreach_edge(gb, route_edge_visitor, &ctx);++ if (ctx.created > 0) {+ char buf[16];+ snprintf(buf, sizeof(buf), "%d", ctx.created);+ cbm_log_info("pass.route_nodes", "created", buf);+ }++ /* Phase 2: match infra Routes to handler Routes by URL path */+ match_infra_routes(gb);+}diff --git a/src/pipeline/pass_usages.c b/src/pipeline/pass_usages.cindex 5746fce7b..a77ec835c 100644--- a/src/pipeline/pass_usages.c+++ b/src/pipeline/pass_usages.c@@ -274,7 +274,11 @@ int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *filcontinue;}- cbm_gbuf_insert_edge(ctx->gbuf, src->id, tgt->id, "USAGE", "{}");+ {+ char uprops[256];+ snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", usage->ref_name);+ cbm_gbuf_insert_edge(ctx->gbuf, src->id, tgt->id, "USAGE", uprops);+ }usage_resolved++;}diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.cindex 66f47eacd..0a0c206dc 100644--- a/src/pipeline/pipeline.c+++ b/src/pipeline/pipeline.c@@ -324,6 +324,33 @@ static void *gh_compute_thread_fn(void *arg) {return NULL;}+/* Extract Route nodes from URL strings found in config files (YAML, HCL, TOML).+ * These are infrastructure-defined endpoints (Cloud Scheduler, Terraform). */+static void cbm_pipeline_extract_infra_routes(cbm_gbuf_t *gbuf, const cbm_file_info_t *files,+ CBMFileResult **result_cache, int file_count) {+ for (int i = 0; i < file_count; i++) {+ if (!result_cache[i]) {+ continue;+ }+ const char *fp = files[i].rel_path;+ if (fp == NULL || (strstr(fp, ".yaml") == NULL && strstr(fp, ".yml") == NULL &&+ strstr(fp, ".tf") == NULL && strstr(fp, ".hcl") == NULL &&+ strstr(fp, ".toml") == NULL)) {+ continue;+ }+ for (int si = 0; si < result_cache[i]->string_refs.count; si++) {+ const CBMStringRef *sr = &result_cache[i]->string_refs.items[si];+ if (sr->kind == CBM_STRREF_URL && sr->value != NULL &&+ strstr(sr->value, "://") != NULL) {+ char route_qn[CBM_ROUTE_QN_SIZE];+ snprintf(route_qn, sizeof(route_qn), "__route__infra__%s", sr->value);+ cbm_gbuf_upsert_node(gbuf, "Route", sr->value, route_qn, fp, 0, 0,+ "{\"source\":\"infra\"}");+ }+ }+ }+}+/* ── Pipeline run ────────────────────────────────────────────────── */int cbm_pipeline_run(cbm_pipeline_t *p) {@@ -545,6 +572,9 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {/* Sync gbuf ID counter after resolve merge */cbm_gbuf_set_next_id(p->gbuf, atomic_load(&shared_ids));+ /* Create Route nodes from infrastructure config URLs */+ cbm_pipeline_extract_infra_routes(p->gbuf, files, result_cache, file_count);+/* Free cached extraction results */for (int i = 0; i < file_count; i++) {if (result_cache[i]) {@@ -746,6 +776,14 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {itoa_buf((int)elapsed_ms(t)));}+ /* Match infra Route URLs (from YAML) to handler Routes (from code) */+ if (!check_cancel(p)) {+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_pipeline_create_route_nodes(p->gbuf);+ cbm_log_info("pass.timing", "pass", "route_match", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));+ }+/* Free prescan cache — no longer needed after httplinks + configlink */if (ctx.prescan_cache) {for (int i = 0; i < ctx.prescan_count; i++) {diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.cindex 1799f8389..750b70e5b 100644--- a/src/pipeline/pipeline_incremental.c+++ b/src/pipeline/pipeline_incremental.c@@ -18,11 +18,13 @@#include "foundation/hash_table.h"#include "foundation/compat.h"#include "foundation/compat_fs.h"+#include "foundation/platform.h"#include <stdlib.h>#include <string.h>#include <sys/stat.h>#include <stdatomic.h>+#include <stdint.h>/* ── Constants ───────────────────────────────────────────────────── */@@ -157,6 +159,15 @@ static void persist_hashes(cbm_store_t *store, const char *project, cbm_file_inf}}+/* ── Registry seed visitor ────────────────────────────────────────── */++/* Callback for cbm_gbuf_foreach_node: add each node to the registry+ * so the resolver can find cross-file symbols during incremental. */+static void registry_visitor(const cbm_gbuf_node_t *node, void *userdata) {+ cbm_registry_t *r = (cbm_registry_t *)userdata;+ cbm_registry_add(r, node->name, node->qualified_name, node->label);+}+/* ── Incremental pipeline entry point ────────────────────────────── */int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_file_info_t *files,@@ -203,25 +214,7 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_filcbm_store_free_file_hashes(stored, stored_count);- /* Delete changed files' nodes from disk DB (edges cascade) */- cbm_store_begin(store);- for (int i = 0; i < file_count; i++) {- if (is_changed[i]) {- cbm_store_delete_nodes_by_file(store, project, files[i].rel_path);- }- }-- /* Delete removed files' nodes + hashes */- for (int i = 0; i < deleted_count; i++) {- cbm_store_delete_nodes_by_file(store, project, deleted[i]);- cbm_store_delete_file_hash(store, project, deleted[i]);- cbm_log_info("incremental.removed", "file", deleted[i]);- free(deleted[i]);- }- free(deleted);- cbm_store_commit(store);-- /* Build list of changed files only */+ /* Build list of changed files */cbm_file_info_t *changed_files = malloc((size_t)n_changed * sizeof(cbm_file_info_t));int ci = 0;for (int i = 0; i < file_count; i++) {@@ -233,65 +226,194 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_filcbm_log_info("incremental.reparse", "files", itoa_buf(ci));- /* Create temp graph buffer + registry for re-parsing changed files */- cbm_gbuf_t *gbuf = cbm_gbuf_new(project, cbm_pipeline_repo_path(p));+ /* ═══════════════════════════════════════════════════════════════+ * RAM-first incremental pipeline:+ * 1. Load entire existing DB into a graph buffer (RAM)+ * 2. Delete stale nodes (changed + removed files) from the gbuf+ * 3. Parallel extract changed files into a FRESH gbuf+ * 4. Populate registry from ALL nodes (existing + fresh) for+ * cross-file resolution accuracy+ * 5. Parallel resolve on changed files (using full registry)+ * 6. Merge fresh gbuf into existing gbuf+ * 7. Delete old DB, dump merged gbuf to disk+ * ═══════════════════════════════════════════════════════════════ */++ struct timespec t;++ /* Step 1: Load existing graph into RAM */+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_gbuf_t *existing = cbm_gbuf_new(project, cbm_pipeline_repo_path(p));+ int load_rc = cbm_gbuf_load_from_db(existing, db_path, project);+ cbm_log_info("incremental.load_db", "rc", itoa_buf(load_rc), "nodes",+ itoa_buf(cbm_gbuf_node_count(existing)), "edges",+ itoa_buf(cbm_gbuf_edge_count(existing)), "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));++ if (load_rc != 0) {+ cbm_log_error("incremental.err", "msg", "load_db_failed");+ cbm_gbuf_free(existing);+ free(changed_files);+ for (int i = 0; i < deleted_count; i++) {+ free(deleted[i]);+ }+ free(deleted);+ cbm_store_close(store);+ return -1;+ }++ /* Close store — done reading, will delete + rewrite at the end */+ cbm_store_close(store);+ store = NULL;++ /* Step 2: Delete changed/removed files' nodes from in-memory graph */+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_log_info("incremental.pre_purge", "nodes", itoa_buf(cbm_gbuf_node_count(existing)), "edges",+ itoa_buf(cbm_gbuf_edge_count(existing)));+ for (int i = 0; i < ci; i++) {+ cbm_gbuf_delete_by_file(existing, changed_files[i].rel_path);+ }+ cbm_log_info("incremental.post_purge", "nodes", itoa_buf(cbm_gbuf_node_count(existing)),+ "edges", itoa_buf(cbm_gbuf_edge_count(existing)));+ for (int i = 0; i < deleted_count; i++) {+ cbm_gbuf_delete_by_file(existing, deleted[i]);+ free(deleted[i]);+ }+ free(deleted);+ cbm_log_info("incremental.purge", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));++ /* Step 3: Extract + resolve directly into EXISTING gbuf.+ * After purge, existing has all unchanged nodes. New nodes from changed+ * files go straight in. The resolver sees ALL nodes — both old and new —+ * so cross-file edges (changed → unchanged AND unchanged → changed) are+ * created correctly. No separate gbuf, no merge, no blind spots. */cbm_registry_t *registry = cbm_registry_new();+ /* Step 4: Populate registry from ALL existing nodes */+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_gbuf_foreach_node(existing, registry_visitor, registry);+ cbm_log_info("incremental.registry_seed", "symbols", itoa_buf(cbm_registry_size(registry)),+ "elapsed_ms", itoa_buf((int)elapsed_ms(t)));+cbm_pipeline_ctx_t ctx = {.project_name = project,.repo_path = cbm_pipeline_repo_path(p),- .gbuf = gbuf,+ .gbuf = existing, /* extract + resolve directly into existing */.registry = registry,.cancelled = cbm_pipeline_cancelled_ptr(p),};- /* Run passes on changed files only */- struct timespec t;- cbm_clock_gettime(CLOCK_MONOTONIC, &t);- cbm_pipeline_pass_definitions(&ctx, changed_files, ci);- cbm_log_info("pass.timing", "pass", "incr_definitions", "elapsed_ms",- itoa_buf((int)elapsed_ms(t)));+ /* Create File nodes for changed files (purge deleted them) */+ for (int i = 0; i < ci; i++) {+ char *file_qn = cbm_pipeline_fqn_compute(project, changed_files[i].rel_path, "__file__");+ if (file_qn) {+ cbm_gbuf_upsert_node(existing, "File", changed_files[i].rel_path, file_qn,+ changed_files[i].rel_path, 0, 0, "{}");+ free(file_qn);+ }+ }++#define MIN_FILES_FOR_PARALLEL_INCR 50+ int worker_count = cbm_default_worker_count(true);+ // NOLINTNEXTLINE(readability-implicit-bool-conversion)+ bool use_parallel = (worker_count > 1 && ci > MIN_FILES_FOR_PARALLEL_INCR);++ if (use_parallel) {+ cbm_log_info("incremental.mode", "mode", "parallel", "workers", itoa_buf(worker_count),+ "changed", itoa_buf(ci));++ _Atomic int64_t shared_ids;+ atomic_init(&shared_ids, cbm_gbuf_next_id(existing));++ CBMFileResult **cache = (CBMFileResult **)calloc(ci, sizeof(CBMFileResult *));+ if (cache) {+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_parallel_extract(&ctx, changed_files, ci, cache, &shared_ids, worker_count);+ cbm_gbuf_set_next_id(existing, atomic_load(&shared_ids));+ cbm_log_info("pass.timing", "pass", "incr_extract", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));++ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_build_registry_from_cache(&ctx, changed_files, ci, cache);+ cbm_log_info("pass.timing", "pass", "incr_registry", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));++ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_parallel_resolve(&ctx, changed_files, ci, cache, &shared_ids, worker_count);+ cbm_gbuf_set_next_id(existing, atomic_load(&shared_ids));+ cbm_log_info("pass.timing", "pass", "incr_resolve", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));++ for (int j = 0; j < ci; j++) {+ if (cache[j]) {+ cbm_free_result(cache[j]);+ }+ }+ free(cache);+ }+ } else {+ cbm_log_info("incremental.mode", "mode", "sequential", "changed", itoa_buf(ci));+ cbm_pipeline_pass_definitions(&ctx, changed_files, ci);+ cbm_pipeline_pass_calls(&ctx, changed_files, ci);+ cbm_pipeline_pass_usages(&ctx, changed_files, ci);+ cbm_pipeline_pass_semantic(&ctx, changed_files, ci);+ }++ cbm_pipeline_pass_k8s(&ctx, changed_files, ci);++ /* Step 6: Post-passes on the full graph (gbuf-only, no disk reads).+ * These operate on the merged graph after extraction + resolve.+ * Unchanged files' post-pass edges were loaded from DB.+ * Changed files' post-pass edges are created here. */cbm_clock_gettime(CLOCK_MONOTONIC, &t);- cbm_pipeline_pass_calls(&ctx, changed_files, ci);- cbm_log_info("pass.timing", "pass", "incr_calls", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));+ cbm_pipeline_pass_tests(&ctx, changed_files, ci);+ cbm_log_info("pass.timing", "pass", "incr_tests", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));cbm_clock_gettime(CLOCK_MONOTONIC, &t);- cbm_pipeline_pass_usages(&ctx, changed_files, ci);- cbm_log_info("pass.timing", "pass", "incr_usages", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));+ cbm_pipeline_pass_decorator_tags(existing, project);+ cbm_log_info("pass.timing", "pass", "incr_decorator_tags", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));+ /* Configlink: key_symbol + dep_imports are gbuf-only (safe).+ * file_refs needs prescan or disk — we set prescan=NULL so it uses+ * the disk fallback ONLY for config files (typically <10 files). */cbm_clock_gettime(CLOCK_MONOTONIC, &t);- cbm_pipeline_pass_semantic(&ctx, changed_files, ci);- cbm_log_info("pass.timing", "pass", "incr_semantic", "elapsed_ms",+ cbm_pipeline_pass_configlink(&ctx);+ cbm_log_info("pass.timing", "pass", "incr_configlink", "elapsed_ms",itoa_buf((int)elapsed_ms(t)));- /* k8s pass runs after semantic (vs. after definitions in the full pipeline) because- * incremental has no parallel extraction phase to position it alongside.- * Note: File→Resource DEFINES edges and cross-file kustomize IMPORTS edges are not- * emitted here — File nodes (from pass_structure) are absent in the incremental gbuf,- * and gbuf_find_by_qn only resolves nodes from changed files. This is a known- * structural limitation of the incremental architecture. */+ /* Httplinks: route discovery uses disk fallback when prescan=NULL.+ * Only reads source for files with Route/Handler labels (~few files). */cbm_clock_gettime(CLOCK_MONOTONIC, &t);- if (cbm_pipeline_pass_k8s(&ctx, changed_files, ci) != 0) {- cbm_log_info("incremental.warn", "msg", "k8s_pass_failed");- }- cbm_log_info("pass.timing", "pass", "incr_k8s", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));+ cbm_pipeline_pass_httplinks(&ctx);+ cbm_log_info("pass.timing", "pass", "incr_httplinks", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));- /* Merge new nodes/edges from gbuf into disk DB */- int new_nodes = cbm_gbuf_node_count(gbuf);- int new_edges = cbm_gbuf_edge_count(gbuf);- cbm_gbuf_merge_into_store(gbuf, store);+ free(changed_files);+ cbm_registry_free(registry);- cbm_log_info("incremental.merged", "nodes", itoa_buf(new_nodes), "edges", itoa_buf(new_edges));+ /* Step 7: Delete old DB, dump merged graph to disk */+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_unlink(db_path);+ char wal[1040];+ char shm[1040];+ snprintf(wal, sizeof(wal), "%s-wal", db_path);+ snprintf(shm, sizeof(shm), "%s-shm", db_path);+ cbm_unlink(wal);+ cbm_unlink(shm);++ int dump_rc = cbm_gbuf_dump_to_sqlite(existing, db_path);+ cbm_log_info("incremental.dump", "rc", itoa_buf(dump_rc), "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));- /* Persist updated file hashes for ALL files */- persist_hashes(store, project, files, file_count);+ /* Persist file hashes for ALL files */+ cbm_store_t *hash_store = cbm_store_open_path(db_path);+ if (hash_store) {+ persist_hashes(hash_store, project, files, file_count);+ cbm_store_close(hash_store);+ }- /* Cleanup */- cbm_gbuf_free(gbuf);- cbm_registry_free(registry);- free(changed_files);- cbm_store_close(store);+ cbm_gbuf_free(existing);cbm_log_info("incremental.done", "elapsed_ms", itoa_buf((int)elapsed_ms(t0)));return 0;diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.hindex 88862ff1d..d0c36f89f 100644--- a/src/pipeline/pipeline_internal.h+++ b/src/pipeline/pipeline_internal.h@@ -19,6 +19,9 @@/* Maximum byte budget for tree-sitter extraction per file */#define CBM_EXTRACT_BUDGET 5000000+/* Route node QN buffer size (must fit __route__METHOD__/full/url/path) */+#define CBM_ROUTE_QN_SIZE 768+/* Time unit conversions */#define CBM_NS_PER_SEC 1000000000LL#define CBM_US_PER_SEC 1000000LL@@ -350,6 +353,11 @@ int cbm_parallel_resolve(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,CBMFileResult **result_cache, _Atomic int64_t *shared_ids,int worker_count);+/* Post-merge: create Route nodes for HTTP_CALLS/ASYNC_CALLS edges that+ * have url_path in properties but point to library functions instead of routes.+ * Re-targets these edges to Route nodes for cross-service traversal. */+void cbm_pipeline_create_route_nodes(cbm_gbuf_t *gb);+/* ── Pass function prototypes ────────────────────────────────────── */int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,diff --git a/src/pipeline/registry.c b/src/pipeline/registry.cindex 93dfb25eb..6b70683cb 100644--- a/src/pipeline/registry.c+++ b/src/pipeline/registry.c@@ -60,6 +60,9 @@ static const char *simple_name(const char *qn) {/* Count common dot-separated prefix segments. */static int common_prefix_len(const char *a, const char *b) {+ if (!a || !b) {+ return 0;+ }int count = 0;while (*a && *b) {/* Find next segment in each */