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
test(repro): deep invariant dives — enclosing-func drift, LSP rescue, discovery/FQN
Martin Vogelb897d5db1e66
diff --git a/Makefile.cbm b/Makefile.cbmindex fbc666760..6ec697b00 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -426,7 +426,10 @@ TEST_REPRO_SRCS = \tests/repro/repro_issue581.c \tests/repro/repro_invariant_calls.c \tests/repro/repro_invariant_graph.c \- tests/repro/repro_invariant_breadth.c+ tests/repro/repro_invariant_breadth.c \+ tests/repro/repro_invariant_enclosing_parity.c \+ tests/repro/repro_invariant_lsp_rescue.c \+ tests/repro/repro_invariant_discovery_fqn.cALL_TEST_SRCS =$(TEST_FOUNDATION_SRCS) $(TEST_EXTRACTION_SRCS) $(TEST_STORE_SRCS) $(TEST_CYPHER_SRCS) $(TEST_MCP_SRCS) $(TEST_DISCOVER_SRCS) $(TEST_GRAPH_BUFFER_SRCS) $(TEST_PIPELINE_SRCS) $(TEST_WATCHER_SRCS) $(TEST_LZ4_SRCS) $(TEST_ZSTD_SRCS) $(TEST_ARTIFACT_SRCS) $(TEST_SQLITE_WRITER_SRCS) $(TEST_GO_LSP_SRCS) $(TEST_C_LSP_SRCS) $(TEST_PHP_LSP_SRCS) $(TEST_CS_LSP_SRCS) $(TEST_CS_LSP_BENCH_SRCS) $(TEST_SCOPE_SRCS) $(TEST_TYPE_REP_SRCS) $(TEST_PY_LSP_SRCS) $(TEST_PY_LSP_BENCH_SRCS) $(TEST_PY_LSP_STRESS_SRCS) $(TEST_PY_LSP_SCALE_SRCS) $(TEST_TS_LSP_SRCS) $(TEST_JAVA_LSP_SRCS) $(TEST_KOTLIN_LSP_SRCS) $(TEST_RUST_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_HTTPD_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_SIMHASH_SRCS) $(TEST_STACK_OVERFLOW_SRCS) $(TEST_INTEGRATION_SRCS)diff --git a/tests/repro/repro_invariant_discovery_fqn.c b/tests/repro/repro_invariant_discovery_fqn.cnew file mode 100644index 000000000..3e2b1bc5b--- /dev/null+++ b/tests/repro/repro_invariant_discovery_fqn.c@@ -0,0 +1,797 @@+/*+ * repro_invariant_discovery_fqn.c — Comprehensive table-driven invariants for:+ *+ * PART A — Discovery hygiene (QUALITY_ANALYSIS.md gap #1)+ * PART B — FQN same-stem distinctness (QUALITY_ANALYSIS.md gap #4)+ *+ * PART A tests EVERY directory name in ALWAYS_SKIP_DIRS (and the most important+ * FAST_SKIP_DIRS entries) to determine which are already guarded and which are+ * not yet in the skip-list (i.e. will be indexed today — RED).+ *+ * PART B tests a table of same-stem file-pair collision cases: which pairs+ * collapse to a single QN (RED) vs which already produce distinct module QNs+ * (GREEN regression guards).+ *+ * No block comments using slash-star inside block comments.+ * All inner documentation uses line comments.+ */++#include "test_framework.h"+#include "repro_harness.h"+#include <store/store.h>+#include <discover/discover.h>+#include "test_helpers.h"++#include <string.h>+#include <stdlib.h>+#include <stdio.h>++/* ═══════════════════════════════════════════════════════════════════════════+ * PART A — DISCOVERY HYGIENE+ * ═══════════════════════════════════════════════════════════════════════════+ *+ * Strategy: for each candidate directory name we create a fixture:+ *+ * <tmpdir>/+ * src/main.py <- control — MUST be discovered+ * <skip_dir>/stub.py <- canary — must NOT be discovered+ *+ * We then call cbm_discover() in CBM_MODE_FULL (NULL opts) so FAST_SKIP_DIRS+ * are NOT applied, giving the most conservative (widest) surface. A directory+ * that survives FULL mode indexing is definitely red. A directory skipped only+ * in non-FULL modes is a softer concern and is noted separately.+ *+ * Each sub-test is a standalone helper that returns 1 (FAIL) / 0 (PASS).+ * The umbrella TEST() walks a table and emits one row per entry so every+ * per-directory result is independently visible in the output.+ *+ * RED entries (discovered today): .claude-worktrees+ * GREEN guards (already in ALWAYS_SKIP_DIRS): all others listed in the table+ */++/* Helper: create fixture, run cbm_discover, check canary. */+/* Returns: 0 canary NOT discovered (correct — directory skipped) */+/* >0 canary WAS discovered (bug — directory NOT in skip-list) */+/* -1 setup error */+static int check_dir_skipped(const char *dir_name, cbm_index_mode_t mode) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "%s/cbm_disc_XXXXXX", cbm_tmpdir());+ if (!cbm_mkdtemp(tmpdir)) {+ return -1;+ }++ /* Control source file — must survive discovery */+ char ctrl[512];+ snprintf(ctrl, sizeof(ctrl), "%s/src/main.py", tmpdir);+ if (th_write_file(ctrl, "def main(): pass\n") != 0) {+ th_rmtree(tmpdir);+ return -1;+ }++ /* Canary file inside the candidate directory */+ char canary[512];+ snprintf(canary, sizeof(canary), "%s/%s/stub.py", tmpdir, dir_name);+ if (th_write_file(canary, "x = 1\n") != 0) {+ th_rmtree(tmpdir);+ return -1;+ }++ cbm_discover_opts_t opts;+ memset(&opts, 0, sizeof(opts));+ opts.mode = mode;++ cbm_file_info_t *files = NULL;+ int count = 0;+ int rc = cbm_discover(tmpdir, (mode == CBM_MODE_FULL) ? NULL : &opts, &files, &count);+ if (rc != 0) {+ th_rmtree(tmpdir);+ return -1;+ }++ /* Build expected canary rel_path prefix: "<dir_name>/" */+ char prefix[256];+ snprintf(prefix, sizeof(prefix), "%s/", dir_name);+ size_t prefix_len = strlen(prefix);++ int canary_found = 0;+ for (int i = 0; i < count; i++) {+ if (strncmp(files[i].rel_path, prefix, prefix_len) == 0) {+ canary_found++;+ }+ }++ cbm_discover_free(files, count);+ th_rmtree(tmpdir);+ return canary_found; /* 0 = skipped (correct), >0 = indexed (bug) */+}++/* ── PART A TEST — ALWAYS_SKIP_DIRS comprehensive table ──────────────────── */++TEST(invariant_discovery_always_skip_dirs) {+ /*+ * Table of directory names that MUST be skipped in CBM_MODE_FULL.+ * Each entry: { name, expected_skipped, is_red }+ * expected_skipped == true → currently in ALWAYS_SKIP_DIRS → GREEN guard+ * is_red == true → NOT currently in skip-list → RED today+ *+ * Source: src/discover/discover.c ALWAYS_SKIP_DIRS array (as of this writing).+ */+ struct { const char *name; int expected_green; } cases[] = {+ /* VCS */+ { ".git", 1 }, /* GREEN — in ALWAYS_SKIP_DIRS */+ { ".hg", 1 }, /* GREEN */+ { ".svn", 1 }, /* GREEN */+ { ".worktrees", 1 }, /* GREEN — bare .worktrees IS in the list */++ /* IDE */+ { ".idea", 1 }, /* GREEN */+ { ".vscode", 1 }, /* GREEN */+ { ".claude", 1 }, /* GREEN */++ /* Python */+ { ".venv", 1 }, /* GREEN */+ { "venv", 1 }, /* GREEN */+ { "__pycache__", 1 }, /* GREEN */+ { ".mypy_cache", 1 }, /* GREEN */+ { ".pytest_cache", 1 }, /* GREEN */+ { ".cache", 1 }, /* GREEN */+ { ".tox", 1 }, /* GREEN */+ { ".nox", 1 }, /* GREEN */+ { ".ruff_cache", 1 }, /* GREEN */+ { ".eggs", 1 }, /* GREEN */+ { ".env", 1 }, /* GREEN */+ { "env", 1 }, /* GREEN */+ { "htmlcov", 1 }, /* GREEN */+ { "site-packages", 1 }, /* GREEN */++ /* JS/TS */+ { "node_modules", 1 }, /* GREEN */+ { ".npm", 1 }, /* GREEN */+ { ".yarn", 1 }, /* GREEN */+ { ".next", 1 }, /* GREEN */+ { ".nuxt", 1 }, /* GREEN */+ { ".svelte-kit", 1 }, /* GREEN */+ { ".angular", 1 }, /* GREEN */+ { ".turbo", 1 }, /* GREEN */+ { ".parcel-cache", 1 }, /* GREEN */+ { ".docusaurus", 1 }, /* GREEN */+ { ".expo", 1 }, /* GREEN */+ { "bower_components", 1 }, /* GREEN */+ { "coverage", 1 }, /* GREEN */+ { ".nyc_output", 1 }, /* GREEN */+ { ".pnpm-store", 1 }, /* GREEN */++ /* Build artifacts */+ { "target", 1 }, /* GREEN */+ { "dist", 1 }, /* GREEN */+ { "obj", 1 }, /* GREEN */+ { "Pods", 1 }, /* GREEN */+ { "temp", 1 }, /* GREEN */+ { "tmp", 1 }, /* GREEN */+ { ".terraform", 1 }, /* GREEN */+ { ".serverless", 1 }, /* GREEN */+ { "bazel-bin", 1 }, /* GREEN */+ { "bazel-out", 1 }, /* GREEN */+ { "bazel-testlogs", 1 }, /* GREEN */++ /* Language caches */+ { ".cargo", 1 }, /* GREEN */+ { ".stack-work", 1 }, /* GREEN */+ { ".dart_tool", 1 }, /* GREEN */+ { "zig-cache", 1 }, /* GREEN */+ { "zig-out", 1 }, /* GREEN */+ { ".metals", 1 }, /* GREEN */+ { ".bloop", 1 }, /* GREEN */+ { ".bsp", 1 }, /* GREEN */+ { ".ccls-cache", 1 }, /* GREEN */+ { ".clangd", 1 }, /* GREEN */+ { "elm-stuff", 1 }, /* GREEN */+ { "_opam", 1 }, /* GREEN */+ { ".cpcache", 1 }, /* GREEN */+ { ".shadow-cljs", 1 }, /* GREEN */++ /* Deploy */+ { ".vercel", 1 }, /* GREEN */+ { ".netlify", 1 }, /* GREEN */+ { "deploy", 1 }, /* GREEN */+ { "deployed", 1 }, /* GREEN */++ /* Misc */+ { ".tmp", 1 }, /* GREEN */+ { "vendor", 1 }, /* GREEN */+ { "vendored", 1 }, /* GREEN */+ { ".qdrant_code_embeddings", 1 }, /* GREEN */++ /* ── RED: NOT yet in ALWAYS_SKIP_DIRS ─────────────────────────── */+ /*+ * .claude-worktrees is the gap documented in QUALITY_ANALYSIS gap #1.+ * The ALWAYS_SKIP_DIRS array only contains ".claude" and ".worktrees"+ * (two separate entries). The compound name ".claude-worktrees" is+ * absent, so cbm_discover() descends into it.+ *+ * expected_green == 0 → we EXPECT the canary to be found (bug present).+ * The ASSERT_EQ at the end treats found-when-expected-found as a RED+ * reproduction, not a test failure.+ *+ * WHY RED: src/discover/discover.c ALWAYS_SKIP_DIRS does not contain+ * ".claude-worktrees". Fix: add ".claude-worktrees" next to ".claude".+ */+ { ".claude-worktrees", 0 }, /* RED — gap #1 */+ };++ int n = (int)(sizeof(cases) / sizeof(cases[0]));+ int failures = 0;++ for (int i = 0; i < n; i++) {+ int result = check_dir_skipped(cases[i].name, CBM_MODE_FULL);++ if (result < 0) {+ printf(" SETUP-ERROR %-32s (could not create fixture)\n",+ cases[i].name);+ failures++;+ continue;+ }++ /* result == 0 → directory was skipped (canary not found)+ * result > 0 → directory was indexed (canary found) */+ int was_skipped = (result == 0);++ if (cases[i].expected_green) {+ /* GREEN guard: we expect it to be skipped. */+ if (!was_skipped) {+ printf(" REGRESSION %-32s canary indexed — was in skip-list but skip broke\n",+ cases[i].name);+ failures++;+ }+ } else {+ /* RED: we expect it NOT to be skipped yet (documenting the bug). */+ if (was_skipped) {+ /* Bug appears fixed — this is now GREEN and should move to the+ * gating suite. Treat as a failure of this repro test. */+ printf(" FIXED? %-32s canary NOT indexed — bug may be fixed\n",+ cases[i].name);+ failures++;+ }+ /* else: canary was found as expected — RED correctly reproduced. */+ }+ }++ /*+ * The test passes when every GREEN guard is still green AND every RED+ * entry is still red (i.e. the bugs are still present and correctly+ * reproduced). If a RED entry becomes GREEN (fixed), the test fails here+ * to force the developer to move it into the gating suite and close the+ * issue.+ */+ ASSERT_EQ(failures, 0);++ PASS();+}++/* ── PART A TEST — FAST_SKIP_DIRS table (mode != CBM_MODE_FULL) ────────────+ *+ * FAST_SKIP_DIRS entries are only skipped when mode != CBM_MODE_FULL.+ * We test them in CBM_MODE_MODERATE to confirm they are guarded.+ * These are all GREEN (expected to be skipped in non-FULL mode).+ *+ * Also a sanity-check: the same entries are NOT skipped in FULL mode+ * (so the test shows they are mode-gated, not universally skipped).+ */+TEST(invariant_discovery_fast_skip_dirs) {+ struct { const char *name; } fast_cases[] = {+ { "generated" },+ { "gen" },+ { "fixtures" },+ { "testdata" },+ { "test_data" },+ { "__tests__" },+ { "__mocks__" },+ { "__snapshots__" },+ { "docs" },+ { "doc" },+ { "examples" },+ { "assets" },+ { "static" },+ { "public" },+ { "third_party" },+ { "thirdparty" },+ { "external" },+ { "migrations" },+ { "build" }, /* build is in FAST_SKIP_DIRS, not ALWAYS */+ { "bin" },+ { "out" },+ { "tools" },+ { "scripts" },+ { "samples" },+ { "e2e" },+ { "integration" },+ { "hack" },+ { "locale" },+ { "locales" },+ { "i18n" },+ { "l10n" },+ { "media" },+ };++ int n = (int)(sizeof(fast_cases) / sizeof(fast_cases[0]));+ int failures = 0;++ for (int i = 0; i < n; i++) {+ /* MODERATE mode: directory should be skipped */+ int moderate = check_dir_skipped(fast_cases[i].name, CBM_MODE_MODERATE);+ if (moderate < 0) {+ printf(" SETUP-ERROR %-32s moderate\n", fast_cases[i].name);+ failures++;+ continue;+ }+ if (moderate != 0) {+ printf(" REGRESSION %-32s not skipped in MODERATE mode\n",+ fast_cases[i].name);+ failures++;+ }++ /* FULL mode: directory should NOT be skipped (mode-gated) */+ int full = check_dir_skipped(fast_cases[i].name, CBM_MODE_FULL);+ if (full < 0) {+ printf(" SETUP-ERROR %-32s full\n", fast_cases[i].name);+ failures++;+ continue;+ }+ if (full == 0) {+ /* Unexpectedly skipped in FULL mode — it crept into ALWAYS_SKIP_DIRS. */+ printf(" UNEXPECTED %-32s skipped in FULL mode (moved to ALWAYS list?)\n",+ fast_cases[i].name);+ /* Not a hard failure — this is informational. */+ }+ }++ ASSERT_EQ(failures, 0);+ PASS();+}++/* ── PART A TEST — Control file must always survive ─────────────────────── */++TEST(invariant_discovery_control_always_found) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "%s/cbm_ctrl_XXXXXX", cbm_tmpdir());+ ASSERT_NOT_NULL(cbm_mkdtemp(tmpdir));++ ASSERT_EQ(0, th_write_file(TH_PATH(tmpdir, "src/main.py"),+ "def main(): pass\n"));++ /* Throw in a few skip-dirs alongside to confirm they don't interfere */+ ASSERT_EQ(0, th_write_file(TH_PATH(tmpdir, "node_modules/a/b.js"),+ "module.exports = {};\n"));+ ASSERT_EQ(0, th_write_file(TH_PATH(tmpdir, ".git/config"),+ "[core]\n"));+ ASSERT_EQ(0, th_write_file(TH_PATH(tmpdir, "vendor/dep/lib.c"),+ "int x = 0;\n"));++ cbm_file_info_t *files = NULL;+ int count = 0;+ int rc = cbm_discover(tmpdir, NULL, &files, &count);+ ASSERT_EQ(0, rc);++ bool main_found = false;+ for (int i = 0; i < count; i++) {+ if (strcmp(files[i].rel_path, "src/main.py") == 0) {+ main_found = true;+ }+ }+ cbm_discover_free(files, count);+ th_rmtree(tmpdir);++ /* Control: must always be found regardless of neighbouring skip-dirs. */+ ASSERT_TRUE(main_found);+ PASS();+}++/* ═══════════════════════════════════════════════════════════════════════════+ * PART B — FQN SAME-STEM DISTINCTNESS+ * ═══════════════════════════════════════════════════════════════════════════+ *+ * Root cause (fqn.c / helpers.c):+ * cbm_pipeline_fqn_compute() calls strip_file_extension() which removes+ * everything from the last '.' in the basename. cbm_fqn_compute() in+ * helpers.c calls strip_ext_len() which scans backwards to find the LAST+ * dot. Both functions are extension-blind: "api.h" and "api.c" both strip+ * to "api", producing the same module QN "<project>.api". Two symbols+ * defined in those files then collide on "<project>.api.<name>"; the upsert+ * overwrites whichever was stored first, leaving only one node.+ *+ * Table entries and RED/GREEN status:+ *+ * 1. api.h + api.c → both strip to "api" → RED (confirmed)+ * 2. svc.h + svc.cpp → both strip to "svc" → RED (same bug)+ * 3. a/util.c + b/util.c → different path prefixes → GREEN (guard)+ * 4. widget.ts + widget.d.ts → strip_ext_len hits last dot:+ * widget.ts → "widget"+ * widget.d.ts → "widget.d"+ * DISTINCT module QNs → GREEN (guard)+ * 5. pkg_a/mod.py + pkg_b/mod.py → different path prefixes → GREEN (guard)+ *+ * Assertion for RED cases: after indexing, cbm_store_find_nodes_by_name()+ * for the shared symbol name returns only 1 node (collapse detected).+ * The ASSERT_GTE(distinct, 2) then fires RED, proving the bug.+ *+ * Assertion for GREEN cases: after indexing, the store holds >= 2 distinct+ * nodes for each shared symbol name (both definitions survive).+ *+ * Each case is its own TEST() so failures are independently visible.+ */++/* ── Helper: count distinct nodes by name for a project ─────────────────── */+static int count_nodes_by_name(cbm_store_t *store, const char *project,+ const char *sym_name) {+ cbm_node_t *nodes = NULL;+ int node_count = 0;+ int rc = cbm_store_find_nodes_by_name(store, project, sym_name,+ &nodes, &node_count);+ if (rc != CBM_STORE_OK) {+ return -1;+ }+ cbm_store_free_nodes(nodes, node_count);+ return node_count;+}++/* ── Helper: count distinct qualified_names among nodes by name ─────────── */+/* Returns the number of DISTINCT qualified_name strings found. */+/* This catches the case where node_count > 1 but QNs collapsed to the same. */+static int count_distinct_qns(cbm_store_t *store, const char *project,+ const char *sym_name) {+ cbm_node_t *nodes = NULL;+ int node_count = 0;+ int rc = cbm_store_find_nodes_by_name(store, project, sym_name,+ &nodes, &node_count);+ if (rc != CBM_STORE_OK) {+ return -1;+ }++ /* Collect all qualified_names into a small stack-array and count uniques */+ /* Use a simple O(n^2) scan — n is tiny (2-3 nodes in fixture tests) */+ enum { MAX_QNS = 32 };+ const char *seen[MAX_QNS];+ int distinct = 0;++ for (int i = 0; i < node_count && distinct < MAX_QNS; i++) {+ const char *qn = nodes[i].qualified_name;+ if (!qn) {+ continue;+ }+ int dup = 0;+ for (int j = 0; j < distinct; j++) {+ if (strcmp(seen[j], qn) == 0) {+ dup = 1;+ break;+ }+ }+ if (!dup) {+ seen[distinct++] = qn;+ }+ }++ cbm_store_free_nodes(nodes, node_count);+ return distinct;+}++/* ── B-1: api.h + api.c — RED ───────────────────────────────────────────── */+/*+ * Both files strip to module QN "<project>.api".+ * api_init declared in api.h and defined in api.c get the SAME QN+ * "<project>.api.api_init". The upsert keeps only the last write.+ *+ * WHY RED:+ * fqn.c strip_file_extension() and helpers.c strip_ext_len() both drop+ * the final extension component unconditionally. Fix: include the+ * extension (or a suffix tag) so ".h" and ".c" produce different module+ * components.+ */+TEST(invariant_fqn_api_h_api_c) {+ static const char api_h[] =+ "void api_init(void);\n"+ "void api_shutdown(void);\n";++ static const char api_c[] =+ "void api_init(void) {}\n"+ "void api_shutdown(void) {}\n";++ static const RFile files[] = {+ {"api.h", api_h},+ {"api.c", api_c},+ };+ static const int nfiles = (int)(sizeof(files) / sizeof(files[0]));++ RProj lp;+ cbm_store_t *store = rh_index_files(&lp, files, nfiles);+ ASSERT_NOT_NULL(store);++ int distinct = count_distinct_qns(store, lp.project, "api_init");++ rh_cleanup(&lp, store);++ /*+ * RED: fqn strips extension so api.h and api.c share module QN.+ * The upsert collapses both api_init definitions to one node.+ * distinct == 1 today, so ASSERT_GTE(distinct, 2) fires RED.+ *+ * GREEN when: the FQN includes the extension or a disambiguating suffix+ * so api.h → "<project>.api_h.api_init" != api.c → "<project>.api_c.api_init".+ */+ ASSERT_GTE(distinct, 2);++ PASS();+}++/* ── B-2: svc.h + svc.cpp — RED ─────────────────────────────────────────── */+/*+ * Same bug as B-1, different extension pair (.h / .cpp).+ * svc_start() declared in svc.h and defined in svc.cpp both get QN+ * "<project>.svc.svc_start".+ *+ * WHY RED: same root cause as B-1.+ */+TEST(invariant_fqn_svc_h_svc_cpp) {+ static const char svc_h[] =+ "void svc_start(void);\n"+ "void svc_stop(void);\n";++ static const char svc_cpp[] =+ "void svc_start(void) {}\n"+ "void svc_stop(void) {}\n";++ static const RFile files[] = {+ {"svc.h", svc_h},+ {"svc.cpp", svc_cpp},+ };+ static const int nfiles = (int)(sizeof(files) / sizeof(files[0]));++ RProj lp;+ cbm_store_t *store = rh_index_files(&lp, files, nfiles);+ ASSERT_NOT_NULL(store);++ int distinct = count_distinct_qns(store, lp.project, "svc_start");++ rh_cleanup(&lp, store);++ /*+ * RED: same extension-stripping collapse as B-1.+ * svc.h and svc.cpp → same module QN → one svc_start node.+ */+ ASSERT_GTE(distinct, 2);++ PASS();+}++/* ── B-3: a/util.c + b/util.c — GREEN regression guard ─────────────────── */+/*+ * Same stem "util", same extension ".c", but different directories.+ * strip_ext produces "util" for both — BUT the path prefix differs:+ * a/util.c → "<project>.a.util"+ * b/util.c → "<project>.b.util"+ * So "util_init" from a/util.c gets QN "<project>.a.util.util_init"+ * and from b/util.c gets "<project>.b.util.util_init" — DISTINCT.+ *+ * Expected: >= 2 distinct QNs for "util_init" (GREEN guard).+ * If this fires RED, the path-prefix component was accidentally collapsed.+ */+TEST(invariant_fqn_different_dirs_same_stem) {+ static const char util_a[] =+ "void util_init(void) {}\n"+ "void util_free(void) {}\n";++ static const char util_b[] =+ "void util_init(void) {}\n"+ "void util_free(void) {}\n";++ static const RFile files[] = {+ {"a/util.c", util_a},+ {"b/util.c", util_b},+ };+ static const int nfiles = (int)(sizeof(files) / sizeof(files[0]));++ RProj lp;+ cbm_store_t *store = rh_index_files(&lp, files, nfiles);+ ASSERT_NOT_NULL(store);++ int n = count_nodes_by_name(store, lp.project, "util_init");++ rh_cleanup(&lp, store);++ /*+ * GREEN: different path prefixes (a/ vs b/) keep QNs distinct.+ * Both definitions must survive as separate nodes.+ * If this fires RED, path-segment handling regressed.+ */+ ASSERT_GTE(n, 2);++ PASS();+}++/* ── B-4: widget.ts + widget.d.ts — GREEN regression guard ─────────────── */+/*+ * .d.ts (TypeScript declaration file) has a compound extension.+ * strip_ext_len in helpers.c scans backwards for the LAST dot:+ * widget.ts → last dot at position 6 → strips to "widget"+ * widget.d.ts → last dot at position 8 → strips to "widget.d"+ *+ * Module QNs:+ * widget.ts → "<project>.widget"+ * widget.d.ts → "<project>.widget.d" (the dot becomes a separator)+ *+ * These are already distinct in the current code, so both definitions+ * survive and this is a GREEN guard. Relates to issue #546 (ambient+ * declaration files getting mixed into the graph).+ *+ * Note: .d.ts files are also matched by the FAST_PATTERNS ".d.ts" filter+ * and skipped in non-FULL mode. This test uses the production pipeline+ * (rh_index_files) which may or may not process widget.d.ts depending on+ * the mode used by rh_open_indexed. We assert on the presence of widget_fn+ * from widget.ts; if widget.d.ts is skipped, n == 1 which is also fine for+ * this GREEN guard (we test that widget.ts survives, not that .d.ts is+ * indexed). The core QN-distinctness property is asserted via the distinct+ * QN check: IF both are indexed, QNs must differ.+ */+TEST(invariant_fqn_ts_vs_dts) {+ static const char widget_ts[] =+ "export function widget_fn(): void {}\n"+ "export function widget_init(): void {}\n";++ static const char widget_dts[] =+ "export function widget_fn(): void;\n"+ "export function widget_init(): void;\n";++ static const RFile files[] = {+ {"widget.ts", widget_ts},+ {"widget.d.ts", widget_dts},+ };+ static const int nfiles = (int)(sizeof(files) / sizeof(files[0]));++ RProj lp;+ cbm_store_t *store = rh_index_files(&lp, files, nfiles);+ ASSERT_NOT_NULL(store);++ cbm_node_t *nodes = NULL;+ int node_count = 0;+ int rc = cbm_store_find_nodes_by_name(store, lp.project, "widget_fn",+ &nodes, &node_count);+ int distinct = 0;+ if (rc == CBM_STORE_OK && node_count > 1) {+ /* Verify all found nodes have DISTINCT qualified_names */+ const char *first_qn = nodes[0].qualified_name;+ for (int i = 1; i < node_count; i++) {+ if (nodes[i].qualified_name &&+ first_qn &&+ strcmp(nodes[i].qualified_name, first_qn) != 0) {+ distinct++;+ }+ }+ }+ int total = node_count;+ if (nodes) {+ cbm_store_free_nodes(nodes, node_count);+ }++ rh_cleanup(&lp, store);++ /* At least the .ts definition must survive (control). */+ ASSERT_GTE(total, 1);++ /* If both were indexed, they must have distinct QNs (no collapse). */+ if (total >= 2) {+ /*+ * GREEN guard: widget.ts → "<project>.widget" and+ * widget.d.ts → "<project>.widget.d" are different module QNs.+ * distinct >= 1 means at least one pair of QNs differs.+ */+ ASSERT_GTE(distinct, 1);+ }++ PASS();+}++/* ── B-5: pkg_a/mod.py + pkg_b/mod.py — GREEN regression guard ─────────── */+/*+ * Same module name "mod" in different Python packages.+ * Path prefixes differ: pkg_a/mod.py → "<project>.pkg_a.mod"+ * pkg_b/mod.py → "<project>.pkg_b.mod"+ * Symbols are distinct. GREEN guard — if this fires, path prefix handling+ * is broken.+ */+TEST(invariant_fqn_python_same_module_different_packages) {+ static const char mod_a[] =+ "def process():\n"+ " return 'a'\n";++ static const char mod_b[] =+ "def process():\n"+ " return 'b'\n";++ static const RFile files[] = {+ {"pkg_a/mod.py", mod_a},+ {"pkg_b/mod.py", mod_b},+ };+ static const int nfiles = (int)(sizeof(files) / sizeof(files[0]));++ RProj lp;+ cbm_store_t *store = rh_index_files(&lp, files, nfiles);+ ASSERT_NOT_NULL(store);++ int n = count_nodes_by_name(store, lp.project, "process");++ rh_cleanup(&lp, store);++ /*+ * GREEN: pkg_a/mod.py and pkg_b/mod.py have different path prefixes.+ * Both "process" definitions must survive with distinct QNs.+ * If this fires RED, path-prefix handling regressed.+ */+ ASSERT_GTE(n, 2);++ PASS();+}++/* ── B-6: mod.go + mod_test.go — GREEN regression guard ─────────────────── */+/*+ * _test.go is a common Go pattern. "mod.go" → module "mod",+ * "mod_test.go" → module "mod_test" (the underscore is part of the stem,+ * not an extension separator). QNs differ because the stem differs.+ * GREEN guard for stem-with-underscore correctness.+ */+TEST(invariant_fqn_go_test_file_stem) {+ static const char mod_go[] =+ "package mod\n"+ "\n"+ "func Setup() {}\n";++ static const char mod_test_go[] =+ "package mod\n"+ "\n"+ "func Setup() {}\n";++ static const RFile files[] = {+ {"mod.go", mod_go},+ {"mod_test.go", mod_test_go},+ };+ static const int nfiles = (int)(sizeof(files) / sizeof(files[0]));++ RProj lp;+ cbm_store_t *store = rh_index_files(&lp, files, nfiles);+ ASSERT_NOT_NULL(store);++ int distinct = count_distinct_qns(store, lp.project, "Setup");++ rh_cleanup(&lp, store);++ /*+ * GREEN: "mod.go" → module "<project>.mod" and+ * "mod_test.go" → module "<project>.mod_test".+ * Both Setup() definitions get distinct QNs — no collapse expected.+ *+ * Note: the pipeline may skip mod_test.go via FAST_PATTERNS (".test.")+ * in non-FULL mode. If distinct == 1, we only have one definition — that+ * is acceptable for this GREEN guard; the key property is no false collapse.+ * We assert >= 1 (at least the production file survived) as the minimum.+ */+ ASSERT_GTE(distinct, 1);++ PASS();+}++/* ═══════════════════════════════════════════════════════════════════════════+ * Suite+ * ═══════════════════════════════════════════════════════════════════════════ */++SUITE(repro_invariant_discovery_fqn) {+ /* Part A — Discovery hygiene */+ RUN_TEST(invariant_discovery_control_always_found);+ RUN_TEST(invariant_discovery_always_skip_dirs);+ RUN_TEST(invariant_discovery_fast_skip_dirs);++ /* Part B — FQN same-stem distinctness */+ RUN_TEST(invariant_fqn_api_h_api_c); /* RED — gap #4 */+ RUN_TEST(invariant_fqn_svc_h_svc_cpp); /* RED — gap #4 */+ RUN_TEST(invariant_fqn_different_dirs_same_stem); /* GREEN guard */+ RUN_TEST(invariant_fqn_ts_vs_dts); /* GREEN guard */+ RUN_TEST(invariant_fqn_python_same_module_different_packages); /* GREEN guard */+ RUN_TEST(invariant_fqn_go_test_file_stem); /* GREEN guard */+}diff --git a/tests/repro/repro_invariant_enclosing_parity.c b/tests/repro/repro_invariant_enclosing_parity.cnew file mode 100644index 000000000..b2647fbe3--- /dev/null+++ b/tests/repro/repro_invariant_enclosing_parity.c@@ -0,0 +1,347 @@+/*+ * repro_invariant_enclosing_parity.c — Enclosing-function detection DRIFT+ * (QUALITY_ANALYSIS gap #3).+ *+ * INVARIANT (same family as repro_invariant_calls.c, broadened to the drift set):+ * For a fixture where EVERY call site sits strictly INSIDE a function/method+ * body, EVERY CALLS edge must be sourced at a node whose label is "Function"+ * or "Method" — never "Module". A Module-sourced CALLS edge proves the+ * enclosing-function walk failed.+ *+ * ROOT CAUSE (verified against the tree, 2026-06-26):+ * helpers.c cbm_find_enclosing_func() (helpers.c:700) walks a call node's+ * ancestry looking for a parent whose tree-sitter type matches a HARD-CODED+ * per-language list, func_kinds_for_lang() (helpers.c:644). Languages NOT in+ * that switch fall through to:+ * func_kinds_generic = {"function_declaration","function_definition",+ * "method_declaration","method_definition"} (helpers.c:641)+ * But lang_specs.c defines `*_func_types[]` (the grammar function node types)+ * for 100+ languages. When a language is (a) absent from the switch AND+ * (b) its grammar's actual enclosing-function node type is NOT one of the four+ * generic strings, cbm_find_enclosing_func() never matches, returns the null+ * node, and cbm_enclosing_func_qn() falls back to the MODULE qn. Every call+ * inside such a function is then attributed to Module. The LSP rescue path+ * (pass_lsp_cross.c) joins on exact caller_qn equality, so a Module qn from+ * tree-sitter can never be reconciled with a Function qn from the LSP — the+ * rescue is silently discarded.+ *+ * THE SWITCH (helpers.c func_kinds_for_lang) COVERS:+ * Go, Python, JS/TS/TSX, Rust, Java, C/C++, Ruby, PHP, Lua, Scala, Kotlin,+ * Elixir, Haskell, OCaml, Zig, Bash, Erlang, C#, Matlab, Lean, Form, Magma,+ * Wolfram.+ * (Perl is NOT in the switch — its drift symptom is already reproduced in+ * repro_invariant_graph.c INVARIANT 4; this file does NOT duplicate Perl.)+ *+ * COMPLETE VERIFIED DRIFT TABLE+ * Columns: lang -> function_node_types (lang_specs.c) -> in switch? ->+ * intersects generic? -> drift verdict.+ * generic = {function_declaration, function_definition, method_declaration,+ * method_definition}.+ *+ * FULLY-DRIFTED (in switch? NO ; generic-intersect? EMPTY -> every body drifts)+ * dart function_signature, method_signature, lambda_expression NO/none -> DRIFT+ * scss mixin_statement, function_statement NO/none -> DRIFT+ * nix function_expression NO/none -> DRIFT+ * commonlisp defun NO/none -> DRIFT+ * fortran function, subroutine, function_statement,+ * subroutine_statement NO/none -> DRIFT+ * cobol program_definition NO/none -> DRIFT+ *+ * PARTIAL DRIFT (in switch? NO ; generic-intersect? NON-EMPTY but the DRIFTED+ * node type below is NOT in generic -> only bodies of that form drift; fixture+ * MUST use the missing form):+ * julia function_definition[gen], short_function_definition[DRIFT] -> use `f(x)=...`+ * sql create_function[DRIFT], function_declaration -> use CREATE FUNCTION+ * verilog function_declaration, task_declaration[DRIFT],+ * function_body_declaration, function_statement -> use `task ...`+ * emacslisp function_definition[gen], macro_definition[DRIFT] -> use `defmacro`+ * cfscript function_declaration, function_expression[DRIFT],+ * arrow_function, method_definition -> use anon function_expression+ * cfml function_declaration, function_expression[DRIFT] -> use anon function_expression+ *+ * NOT DRIFTED (intersect generic via a leading generic node type; plain+ * function bodies resolve through the generic fallback even though absent from+ * the switch) — e.g. objc/swift/groovy/r/fsharp/vim/elm/d/solidity/gdscript/+ * gleam/crystal/templ/... all lead with function_declaration|function_definition.+ *+ * SECOND, INDEPENDENT GAP (callee resolution) — IMPORTANT for the fixer:+ * Some drifted langs ALSO have no callee-resolution branch in extract_calls.c+ * (test_lang_contract.c marks expected_calls=false for: commonlisp, emacslisp,+ * dart-as-of-that-table, solidity, ada, fennel, fsharp, powershell, clojure...).+ * For those the fixture produces ZERO CALLS edges, so this test REDs at the+ * "no CALLS edges" guard, NOT at the Module-source check. That is STILL the+ * correct expected-RED state, but fixing gap #3 (the enclosing-func switch)+ * alone will NOT flip them green — the missing callee branch must also land.+ * The cleanest pure-#3 reproductions (a CALLS edge forms, but it is+ * Module-sourced) are FORTRAN, SCSS, SQL, VERILOG, JULIA, NIX. Each per-lang+ * comment states which failure class applies.+ *+ * FIX (single root cause for the FULLY/PARTIAL-drifted set):+ * Replace the hard-coded func_kinds_for_lang switch with a lookup of the+ * language's spec->func_types (lang_specs.c) so cbm_find_enclosing_func uses+ * the SAME node-type list the definition walker uses. Then add the missing+ * callee branches for the second-gap langs separately.+ *+ * ASSERTION (per edge): for every CALLS edge e,+ * cbm_store_find_node_by_id(store, e.source_id, &src) == CBM_STORE_OK AND+ * (src.label == "Function" || src.label == "Method"); i.e. module_sourced == 0.+ * PLUS: at least one CALLS edge must exist (zero edges is a no-signal fixture).+ *+ * NOTE: block comments use line-comment style internally; no nested block+ * comment opener appears inside this comment.+ */++#include "test_framework.h"+#include "repro_harness.h"+#include <store/store.h>++#include <string.h>++/* ── Table-driven model ─────────────────────────────────────────────────── */++typedef struct {+ CBMLanguage lang;+ const char *name; /* human-readable tag for failure messages */+ const char *file; /* fixture filename (extension drives language detection) */+ const char *src; /* fixture source: a call strictly inside a drifted function */+} parity_case_t;++/*+ * run_parity_case+ *+ * Index the single fixture file through the production pipeline, collect all+ * CALLS edges, and assert each edge's source node is callable-labelled.+ *+ * Returns 0 (PASS) when >=1 CALLS edge exists and ALL are callable-sourced.+ * Returns 1 (FAIL) when zero CALLS edges exist OR any edge is Module-sourced.+ *+ * Both failure modes are "expected RED" for the drift set; the printed reason+ * distinguishes the enclosing-func drift (Module-sourced) from the co-occurring+ * no-edge gap (callee resolution).+ */+static int run_parity_case(const parity_case_t *c) {+ const char *RED = "\033[31m";+ const char *RST = "\033[0m";++ RFile files[1] = {{c->file, c->src}};+ RProj lp;+ cbm_store_t *store = rh_index_files(&lp, files, 1);+ if (!store) {+ printf(" %sFAIL%s [%s] rh_index_files returned NULL\n", RED, RST, c->name);+ return 1;+ }++ cbm_edge_t *edges = NULL;+ int nedges = 0;+ int rc = cbm_store_find_edges_by_type(store, lp.project, "CALLS", &edges, &nedges);+ if (rc != CBM_STORE_OK) {+ printf(" %sFAIL%s [%s] cbm_store_find_edges_by_type rc=%d\n", RED, RST, c->name, rc);+ rh_cleanup(&lp, store);+ return 1;+ }++ if (nedges == 0) {+ /* RED for the right family — but via the no-edge (callee resolution)+ * gap, not the Module-source drift. Stated explicitly so the #3 fixer+ * is not misled into thinking the enclosing-func fix alone flips this. */+ printf(" %sFAIL%s [%s] no CALLS edges (callee-resolution gap; gap #3 fix "+ "alone will not flip this)\n",+ RED, RST, c->name);+ cbm_store_free_edges(edges, nedges);+ rh_cleanup(&lp, store);+ return 1;+ }++ int module_sourced = 0;+ for (int i = 0; i < nedges; i++) {+ cbm_node_t src;+ if (cbm_store_find_node_by_id(store, edges[i].source_id, &src) != CBM_STORE_OK) {+ continue; /* dangling edge — not this invariant's concern */+ }+ const char *lbl = src.label ? src.label : "(null)";+ if (strcmp(lbl, "Function") != 0 && strcmp(lbl, "Method") != 0) {+ module_sourced++;+ }+ }++ cbm_store_free_edges(edges, nedges);+ rh_cleanup(&lp, store);++ if (module_sourced > 0) {+ printf(" %sFAIL%s [%s] %d/%d CALLS edge(s) Module-sourced "+ "(enclosing-func drift; gap #3)\n",+ RED, RST, c->name, module_sourced, nedges);+ return 1;+ }+ return 0;+}++/* ── Fixtures (one drifted function CONTAINING a call to another) ────────── */++/*+ * FORTRAN — FULLY DRIFTED. grammar type `function` is not in generic, absent+ * from switch. Contract table marks expected_calls=true, so a CALLS edge DOES+ * form: this is the CLEANEST pure-#3 reproduction — the edge is Module-sourced.+ */+static const parity_case_t case_fortran = {+ CBM_LANG_FORTRAN, "Fortran", "a.f90",+ "function helper(x) result(y)\n"+ " integer, intent(in) :: x\n"+ " integer :: y\n"+ " y = x + 1\n"+ "end function helper\n"+ "\n"+ "function run(n) result(total)\n"+ " integer, intent(in) :: n\n"+ " integer :: total\n"+ " total = helper(n)\n"+ "end function run\n"};++/*+ * SCSS — FULLY DRIFTED. function_statement / mixin_statement not in generic,+ * absent from switch. The call (`double(...)`) sits inside an @function body.+ */+static const parity_case_t case_scss = {+ CBM_LANG_SCSS, "SCSS", "a.scss",+ "@function double($x) {\n"+ " @return $x * 2;\n"+ "}\n"+ "\n"+ "@function quad($x) {\n"+ " @return double($x) + double($x);\n"+ "}\n"};++/*+ * SQL — PARTIAL DRIFT. create_function is the missing (DRIFT) form. The inner+ * call to helper() lives inside the CREATE FUNCTION body.+ */+static const parity_case_t case_sql = {+ CBM_LANG_SQL, "SQL", "a.sql",+ "CREATE FUNCTION helper(x INTEGER) RETURNS INTEGER AS $$\n"+ " SELECT x + 1;\n"+ "$$ LANGUAGE sql;\n"+ "\n"+ "CREATE FUNCTION run(n INTEGER) RETURNS INTEGER AS $$\n"+ " SELECT helper(n);\n"+ "$$ LANGUAGE sql;\n"};++/*+ * VERILOG — PARTIAL DRIFT. task_declaration is the missing (DRIFT) form. The+ * call to the subroutine `do_log` sits inside a `task` body. (.sv routes to+ * CBM_LANG_VERILOG via EXT_TABLE.)+ */+static const parity_case_t case_verilog = {+ CBM_LANG_VERILOG, "Verilog", "a.sv",+ "module m;\n"+ " task do_log(input int v);\n"+ " $display(\"v=%0d\", v);\n"+ " endtask\n"+ "\n"+ " task run(input int n);\n"+ " do_log(n);\n"+ " endtask\n"+ "endmodule\n"};++/*+ * JULIA — PARTIAL DRIFT. short_function_definition (`f(x) = ...`) is the missing+ * (DRIFT) form; the plain `function ... end` form would resolve via generic+ * `function_definition`. The call to helper() is in the short-form body.+ */+static const parity_case_t case_julia = {+ CBM_LANG_JULIA, "Julia", "a.jl",+ "helper(x) = x + 1\n"+ "run(n) = helper(n)\n"};++/*+ * NIX — FULLY DRIFTED. function_expression (`x: body`) not in generic, absent+ * from switch. The call (`double 21`) sits inside a lambda body bound in a let.+ */+static const parity_case_t case_nix = {+ CBM_LANG_NIX, "Nix", "a.nix",+ "let\n"+ " double = x: x * 2;\n"+ " run = n: double n;\n"+ "in run 21\n"};++/*+ * COMMONLISP — FULLY DRIFTED (defun not in generic) AND second-gap: the lisp+ * `list_lit` callee head is a sym_lit, so extract_calls forms NO CALLS edge+ * (test_lang_contract expected_calls=false). Expect RED via the no-edge guard;+ * gap #3 fix alone will not flip it.+ */+static const parity_case_t case_commonlisp = {+ CBM_LANG_COMMONLISP, "CommonLisp", "a.lisp",+ "(defun helper (x)\n"+ " (* x 2))\n"+ "\n"+ "(defun run ()\n"+ " (helper 21))\n"};++/*+ * EMACSLISP — PARTIAL DRIFT: defun maps to function_definition (generic, NOT+ * drifted), so the drift form is macro_definition (`defmacro`). ALSO second-gap:+ * the `list` callee head is a `symbol`, so no CALLS edge forms+ * (test_lang_contract expected_calls=false). The call lives inside a defmacro+ * body. Expect RED via the no-edge guard.+ */+static const parity_case_t case_emacslisp = {+ CBM_LANG_EMACSLISP, "EmacsLisp", "a.el",+ "(defmacro run (n)\n"+ " \"Expand to a helper call.\"\n"+ " (helper n))\n"};++/*+ * DART — FULLY DRIFTED (function_signature/method_signature not in generic).+ * The call to helper() is inside run()'s body. Dart additionally has a+ * historically-noted callee gap (test_lang_contract expected_calls=false);+ * if no edge forms this REDs via the no-edge guard, otherwise via Module-source.+ */+static const parity_case_t case_dart = {+ CBM_LANG_DART, "Dart", "a.dart",+ "void helper() {\n"+ " print('helper');\n"+ "}\n"+ "\n"+ "void run() {\n"+ " helper();\n"+ "}\n"};++/*+ * COBOL — FULLY DRIFTED (program_definition not in generic). The CALL statement+ * lives inside the PROCEDURE DIVISION of a program_definition body.+ */+static const parity_case_t case_cobol = {+ CBM_LANG_COBOL, "COBOL", "a.cob",+ " IDENTIFICATION DIVISION.\n"+ " PROGRAM-ID. RUNPROG.\n"+ " PROCEDURE DIVISION.\n"+ " CALL 'HELPER'.\n"+ " STOP RUN.\n"};++/* ── Per-language TEST wrappers (one each so RED/GREEN shows per lang) ───── */++TEST(repro_enclosing_parity_fortran) { return run_parity_case(&case_fortran); }+TEST(repro_enclosing_parity_scss) { return run_parity_case(&case_scss); }+TEST(repro_enclosing_parity_sql) { return run_parity_case(&case_sql); }+TEST(repro_enclosing_parity_verilog) { return run_parity_case(&case_verilog); }+TEST(repro_enclosing_parity_julia) { return run_parity_case(&case_julia); }+TEST(repro_enclosing_parity_nix) { return run_parity_case(&case_nix); }+TEST(repro_enclosing_parity_commonlisp) { return run_parity_case(&case_commonlisp); }+TEST(repro_enclosing_parity_emacslisp) { return run_parity_case(&case_emacslisp); }+TEST(repro_enclosing_parity_dart) { return run_parity_case(&case_dart); }+TEST(repro_enclosing_parity_cobol) { return run_parity_case(&case_cobol); }++/* ── Suite ──────────────────────────────────────────────────────────────── */++SUITE(repro_invariant_enclosing_parity) {+ RUN_TEST(repro_enclosing_parity_fortran);+ RUN_TEST(repro_enclosing_parity_scss);+ RUN_TEST(repro_enclosing_parity_sql);+ RUN_TEST(repro_enclosing_parity_verilog);+ RUN_TEST(repro_enclosing_parity_julia);+ RUN_TEST(repro_enclosing_parity_nix);+ RUN_TEST(repro_enclosing_parity_commonlisp);+ RUN_TEST(repro_enclosing_parity_emacslisp);+ RUN_TEST(repro_enclosing_parity_dart);+ RUN_TEST(repro_enclosing_parity_cobol);+}diff --git a/tests/repro/repro_invariant_lsp_rescue.c b/tests/repro/repro_invariant_lsp_rescue.cnew file mode 100644index 000000000..f0ff9e2cb--- /dev/null+++ b/tests/repro/repro_invariant_lsp_rescue.c@@ -0,0 +1,250 @@+/*+ * repro_invariant_lsp_rescue.c — QUALITY_ANALYSIS gap #5 / #5a:+ * the LSP rescue cannot recover a bad tree-sitter caller QN because the+ * join key is exact caller-QN string equality.+ *+ * THE BLOCKER (file:func:line):+ * cbm_pipeline_find_lsp_resolution (src/pipeline/lsp_resolve.h:48)+ * joins each LSP-resolved call (CBMResolvedCall) to the tree-sitter call+ * (CBMCall) with EXACT string equality on the caller QN:+ *+ * lsp_resolve.h:65:+ * if (strcmp(rc->caller_qn, call->enclosing_func_qn) != 0)+ * continue;+ *+ * Consumed by:+ * - src/pipeline/pass_calls.c:369 (sequential pipeline,+ * resolve_single_call → emit_classified_edge)+ * - src/pipeline/pass_parallel.c:1797 (parallel pipeline)+ *+ * When tree-sitter's enclosing-func walk FAILS, cbm_enclosing_func_qn+ * falls back to the MODULE QN, so call->enclosing_func_qn is the module+ * QN. The C/C++ LSP cross resolver (internal/cbm/lsp/c_lsp.c) builds its+ * OWN enclosing QN from scope resolution — for an out-of-line method+ * Foo::bar it produces the real method QN "<proj>.<module>.Foo.bar"+ * (c_process_function, c_lsp.c:4138-4143) and emits a CBMResolvedCall+ * with caller_qn = that real method QN, strategy = "lsp_direct" /+ * "lsp_implicit_this" / "lsp_type_dispatch", confidence 0.95+ * (c_emit_resolved_call, c_lsp.c:3287-3296). 0.95 is well above+ * CBM_LSP_CONFIDENCE_FLOOR (0.6f, lsp_resolve.h:36).+ *+ * So the LSP HAS the correct caller, but the join key on the+ * tree-sitter side is the MODULE QN. module-QN != real-method-QN, the+ * strcmp at lsp_resolve.h:65 never matches, find_lsp_resolution returns+ * NULL, the LSP rescue branch (pass_calls.c:370-385) is skipped, and the+ * edge falls through to the registry resolver — staying Module-sourced+ * with a registry strategy. The LSP rescue is silently DISCARDED.+ *+ * FIXTURE RATIONALE (C++ out-of-line method — the #554 family):+ * A free function helper() and a class Processor with an OUT-OF-LINE+ * method definition Processor::run that calls helper(v). For the+ * out-of-line method body, tree-sitter's cbm_find_enclosing_func cannot+ * walk the call-expression's ancestry back to a node whose type is in+ * func_kinds_cpp = {"function_definition"} in a way that yields the+ * class-qualified method QN, so cbm_enclosing_func_qn falls back to the+ * module QN (issue #554 / extract_defs.c + c_lsp.c dominate the+ * QUALITY_ANALYSIS Module-sourced-CALLS top-file list). C/C++ has a+ * cross-file LSP wired up (cbm_pxc_has_cross_lsp, pass_lsp_cross.c:281),+ * so the LSP DOES resolve the real Processor::run caller. This is the+ * cleanest fixture where tree-sitter attribution lands on Module but the+ * LSP resolves the real enclosing function — exactly gap #5a.+ *+ * EXPECTED vs ACTUAL:+ * EXPECTED (correct, what the fix must produce): the helper() CALLS edge+ * is sourced at the real callable node Processor::run (label+ * "Function"/"Method"), via the LSP rescue, and its properties_json+ * carries the LSP strategy marker (strategy starts with "lsp_") and the+ * LSP confidence (0.95).+ * ACTUAL (today, RED): the join discards the LSP result, so the edge is+ * Module-sourced and its properties carry a registry strategy+ * (same_module / import_map / ...), never an "lsp_" strategy.+ *+ * This file deliberately complements repro_invariant_calls.c: that file+ * asserts the broad "zero Module-sourced CALLS" invariant; THIS file+ * pins the *mechanism* — that the LSP rescue specifically is the missing+ * recovery, by also asserting the rescued edge preserves the LSP+ * strategy/confidence in its properties_json (gap #5a, second assertion).+ *+ * NOTE: line comments only inside this header (no block comments inside a+ * block comment, per coding rules).+ */++#include "test_framework.h"+#include "repro_harness.h"+#include <store/store.h>++#include <string.h>++/* ── Fixture ────────────────────────────────────────────────────────────── */++/*+ * Out-of-line method Processor::run calls the free function helper().+ * - helper : free function, definition-style body.+ * - Processor::run: OUT-OF-LINE method definition. tree-sitter's+ * enclosing-func walk falls back to the module QN here+ * (#554), but the C++ LSP resolves caller = Processor::run.+ * The call we care about is `helper(v)` inside Processor::run.+ */+static const char kCppOutOfLine[] =+ "static int helper(int x) { return x * 2; }\n"+ "\n"+ "class Processor {\n"+ "public:\n"+ " int run(int v);\n"+ "};\n"+ "\n"+ "int Processor::run(int v) {\n"+ " return helper(v);\n"+ "}\n";++/* ── Locate the helper() CALLS edge ─────────────────────────────────────── */++/*+ * find_call_edge_to_helper+ *+ * Scan all CALLS edges and return (by out-params) the one whose TARGET node+ * qualified_name ends in ".helper" — that is the `helper(v)` call site inside+ * Processor::run. Copies the source node and the edge's properties_json into+ * caller-owned buffers so the caller can assert after freeing the edge array.+ *+ * Returns 1 if found, 0 otherwise.+ */+static int find_call_edge_to_helper(cbm_store_t *store, const char *project,+ cbm_node_t *out_src, char *out_props,+ size_t props_cap) {+ cbm_edge_t *edges = NULL;+ int nedges = 0;+ if (cbm_store_find_edges_by_type(store, project, "CALLS", &edges, &nedges)+ != CBM_STORE_OK) {+ return 0;+ }++ int found = 0;+ for (int i = 0; i < nedges; i++) {+ cbm_node_t tgt;+ if (cbm_store_find_node_by_id(store, edges[i].target_id, &tgt)+ != CBM_STORE_OK) {+ continue;+ }+ const char *tqn = tgt.qualified_name ? tgt.qualified_name : "";+ size_t tlen = strlen(tqn);+ const char *suffix = ".helper";+ size_t slen = strlen(suffix);+ if (tlen < slen || strcmp(tqn + tlen - slen, suffix) != 0) {+ continue;+ }+ /* This is the helper() call edge. Capture its source node + props. */+ if (cbm_store_find_node_by_id(store, edges[i].source_id, out_src)+ == CBM_STORE_OK) {+ const char *props = edges[i].properties_json+ ? edges[i].properties_json : "{}";+ snprintf(out_props, props_cap, "%s", props);+ found = 1;+ }+ break;+ }++ cbm_store_free_edges(edges, nedges);+ return found;+}++/* ── #5: rescued edge must be callable-sourced via the LSP caller ───────── */++/*+ * repro_invariant_lsp_rescue_source+ *+ * Expected: RED on current code.+ *+ * The helper() call inside the out-of-line method Processor::run must be+ * sourced at the real callable node (label "Function" or "Method") — the+ * LSP resolves caller = Processor::run, which should rescue the bad+ * tree-sitter Module attribution.+ *+ * Today the join in cbm_pipeline_find_lsp_resolution (lsp_resolve.h:65)+ * requires rc->caller_qn == call->enclosing_func_qn; tree-sitter supplies+ * the MODULE QN, the LSP supplies the real method QN, they never strcmp+ * equal, the LSP rescue is discarded, and the edge stays Module-sourced.+ * So src.label == "Module" → this assertion FAILS (RED), proving the bug.+ */+TEST(repro_invariant_lsp_rescue_source) {+ RProj lp;+ cbm_store_t *store = rh_index(&lp, "main.cpp", kCppOutOfLine);+ ASSERT_TRUE(store != NULL);++ cbm_node_t src;+ char props[1024];+ int found = find_call_edge_to_helper(store, lp.project, &src,+ props, sizeof(props));++ /* Sanity: the helper() CALLS edge must exist at all, else no signal. */+ ASSERT_TRUE(found == 1);++ const char *lbl = src.label ? src.label : "(null)";++ /*+ * INVARIANT (RED today): the edge is sourced at the real callable+ * (Function/Method), NOT at the Module. The only path that can produce+ * this for an out-of-line method whose tree-sitter enclosing is Module+ * is the LSP rescue — which the exact-QN join discards today.+ */+ ASSERT_TRUE(strcmp(lbl, "Function") == 0 || strcmp(lbl, "Method") == 0);++ rh_cleanup(&lp, store);+ return 0;+}++/* ── #5a: rescued edge must preserve the LSP strategy/confidence ────────── */++/*+ * repro_invariant_lsp_rescue_props+ *+ * Expected: RED on current code.+ *+ * Per QUALITY_ANALYSIS gap #5a, when the LSP rescues a call the emitted+ * edge must record the LSP provenance. pass_calls.c:374-381 copies+ * res.strategy = lsp->strategy and res.confidence = lsp->confidence into+ * the edge, and emit_classified_edge writes them into properties_json as+ * {"callee":"...","confidence":0.95,"strategy":"lsp_...","candidates":1}+ * (pass_calls.c:336-340). The C++ LSP strategies are all "lsp_"-prefixed+ * (lsp_direct / lsp_implicit_this / lsp_type_dispatch / lsp_virtual_dispatch+ * / lsp_base_dispatch / lsp_smart_ptr_dispatch, c_lsp.c:3390-3658) at+ * confidence 0.95.+ *+ * Today the rescue never fires (join discarded), so the surviving edge is+ * registry-resolved and its strategy is a registry strategy (same_module /+ * import_map / ...), never "lsp_". The substring "\"strategy\":\"lsp_" is+ * therefore ABSENT from properties_json → this assertion FAILS (RED).+ *+ * If a future change emits the rescued edge but with different property+ * keys, update the marker here; the source-label invariant in the test+ * above is the primary, key-independent signal.+ */+TEST(repro_invariant_lsp_rescue_props) {+ RProj lp;+ cbm_store_t *store = rh_index(&lp, "main.cpp", kCppOutOfLine);+ ASSERT_TRUE(store != NULL);++ cbm_node_t src;+ char props[1024];+ int found = find_call_edge_to_helper(store, lp.project, &src,+ props, sizeof(props));+ ASSERT_TRUE(found == 1);++ /*+ * INVARIANT (RED today): the rescued edge's properties_json carries the+ * LSP strategy marker. We look for a "strategy" value beginning with+ * "lsp_" — the prefix shared by every C/C++ LSP strategy string.+ */+ int has_lsp_strategy = (strstr(props, "\"strategy\":\"lsp_") != NULL);+ ASSERT_TRUE(has_lsp_strategy);++ rh_cleanup(&lp, store);+ return 0;+}++/* ── Suite ──────────────────────────────────────────────────────────────── */++SUITE(repro_invariant_lsp_rescue) {+ RUN_TEST(repro_invariant_lsp_rescue_source);+ RUN_TEST(repro_invariant_lsp_rescue_props);+}diff --git a/tests/repro/repro_main.c b/tests/repro/repro_main.cindex a14753688..b4d9ff129 100644--- a/tests/repro/repro_main.c+++ b/tests/repro/repro_main.c@@ -63,6 +63,9 @@ extern void suite_repro_new_cypher_limit_zero(void);extern void suite_repro_invariant_calls(void);extern void suite_repro_invariant_graph(void);extern void suite_repro_invariant_breadth(void);+extern void suite_repro_invariant_enclosing_parity(void);+extern void suite_repro_invariant_lsp_rescue(void);+extern void suite_repro_invariant_discovery_fqn(void);int main(void) {/* Unbuffered: a reproduction may crash/_exit (or a sanitizer may _exit on a@@ -111,6 +114,9 @@ int main(void) {RUN_SUITE(repro_invariant_calls);RUN_SUITE(repro_invariant_graph);RUN_SUITE(repro_invariant_breadth);+ RUN_SUITE(repro_invariant_enclosing_parity);+ RUN_SUITE(repro_invariant_lsp_rescue);+ RUN_SUITE(repro_invariant_discovery_fqn);TEST_SUMMARY();}